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?
Asked
Active
Viewed 8.6k times
81
-
[Varargs In Java: Variable Argument Method In Java](http://viralpatel.net/blogs/varargs-in-java-variable-argument-method-in-java-5/) – Grijesh Chauhan May 25 '13 at 10:21
-
1I am not sure if I understand your question correctly. Is it `method(String... length)` or `method(int length, String... param)`, or maybe something else? – Pshemo May 25 '13 at 10:27
5 Answers
96
String...
equals a String[]
So just convert your list
to a String[]
and you should be fine.
-
20Additional note to OP: if you ever have a method that takes Object..., this scheme won't work because the String[] will be understood as one Object. – Marko Topolnik May 25 '13 at 10:46
-
42
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.

Alpesh Gediya
- 3,706
- 1
- 25
- 38
-
8This also works: `list.toArray(new Foo[]{})`; useful if you don't want to store a list in additional variable. – liosedhel May 30 '14 at 06:43
-
What is this `Foo` thing ? I used a `String` instead as in `getUnsecuredPaths().toArray(new String[]{})` – Stephane Oct 03 '18 at 14:56
-
1Obviously this is an old comment, but to anyone else reading this who has the same question; `Foo` is a pretty common term used in programming as a placeholder for a value that can change. It is useful when you're providing a generic example such as the one above, as `Foo` can be replaced by whichever object you're working with (in this case, a String). You may also see `Bar` used when there are multiple placeholders in an example. – Andy Shearer Feb 26 '21 at 12:19
24
You can use stream
in java 8.
String[] array = list.stream().toArray(String[]::new);
Then the array can be used in the ...args
position.

Searene
- 25,920
- 39
- 129
- 186
-
-
FYI, if developing for Android streams require API 24 and jdk 1.8, so make sure its set up in your manifest and project settings. – Shane Sepac Apr 04 '18 at 23:52
1
in case of long (primitive value)
long[] longArray = list.stream().mapToLong(o->g.getValue()).toArray();
when getValue()
returns a long type

Procrastinator
- 2,526
- 30
- 27
- 36

Samuel Morales
- 21
- 2
1
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);

avi.elkharrat
- 6,100
- 6
- 41
- 47