81

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?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
java_geek
  • 17,585
  • 30
  • 91
  • 113
  • [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
  • 1
    I 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 Answers5

96

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

Svish
  • 152,914
  • 173
  • 462
  • 620
FloF
  • 1,167
  • 9
  • 7
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
  • 8
    This 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
  • 1
    Obviously 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
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
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