How to convert a List to variable argument parameter java

前端 未结 3 1966
情深已故
情深已故 2021-02-03 17:09

I have a method which takes a variable length string (String...) as parameter. I have a List with me. How can I pass this to the method as argument?

相关标签:
3条回答
  • 2021-02-03 17:19

    You can use stream in java 8.

    String[] array = list.stream().toArray(String[]::new);
    

    Then the array can be used in the ...args position.

    0 讨论(0)
  • 2021-02-03 17:21

    String ... and String[] are identical If you convert your list to array.

    using

    Foo[] array = list.toArray(new Foo[list.size()]);
    

    or

    Foo[] array = new Foo[list.size()];
    list.toArray(array);
    

    then use that array as String ... argument to function.

    0 讨论(0)
  • 2021-02-03 17:41

    String... equals a String[] So just convert your list to a String[] and you should be fine.

    0 讨论(0)
提交回复
热议问题