How to convert a List to variable argument parameter java

心已入冬 提交于 2019-12-03 14:17:50

问题


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


回答1:


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




回答2:


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.




回答3:


You can use stream in java 8.

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

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



来源:https://stackoverflow.com/questions/16748470/how-to-convert-a-list-to-variable-argument-parameter-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!