How to convert a List to variable argument parameter java

JavaListVariadic Functions

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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.

Solution 3 - Java

You can use stream in java 8.

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

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

Solution 4 - Java

in case of long (primitive value)

long[] longArray = list.stream().mapToLong(o->g.getValue()).toArray();

when getValue() returns a long type

Solution 5 - Java

For Java > 8

You can very well use the toArray method very simply, as in:

String[] myParams = myList.toArray(String[]::new);

Streaming becomes really interesting when the elements of the List must be transformed, filtered or else before being converted to Array:

String[] myMappedAndFilteredParams = myList.stream()
                                 .map(param -> param + "some_added_stuff")
                                 .filter(param -> param.contains("some very important info"))
                                 .collect(toList())
                                 .toArray(String[]::new);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionjava_geekView Question on Stackoverflow
Solution 1 - JavaFloFView Answer on Stackoverflow
Solution 2 - JavaAlpesh GediyaView Answer on Stackoverflow
Solution 3 - JavaSeareneView Answer on Stackoverflow
Solution 4 - JavaSamuel MoralesView Answer on Stackoverflow
Solution 5 - Javaavi.elkharratView Answer on Stackoverflow