BamDoya
BamDoya

Reputation: 83

How so I pass a collection of Strings to a method with (String... Strings) signature?

I want to do something like this:

ArrayList<String> strings = new ArrayList<>();

//build a collection of Strings

callMethod(strings);

The "callMethod" is legacy (in a legacy project), so I cannot change it.

It's signature is this:

private void callMethod(String... input){

// and so forth...

How do I pass the collection of Strings to the callMethod method?

Upvotes: 1

Views: 742

Answers (4)

Jimmy
Jimmy

Reputation: 1051

    public void method() {
        
        ArrayList<String> strings = new ArrayList<>();
        
        //1. calling method by passing the array
        callMethod(strings.toArray(new String[strings.size()]));

        //2. Using stream method to convert list into array
        callMethod(strings.stream().toArray(String[]::new));
    }
    
    // method having array of String as parameter
    public static void callMethod(String... input){
        
        // TODO Method stub
    }

Upvotes: 0

M A
M A

Reputation: 72884

Just convert the list to an array of Strings (varargs turns into an array under the hood: "If the formal parameter is a variable arity parameter, then the declared type is an array type specified by §10.2."):

callMethod(strings.toArray(new String[0]));

Upvotes: 7

deHaar
deHaar

Reputation: 18588

If you have a method with varargs (variable arguments), you have 2 options:

  1. pass each item of the collection as a single argument or
  2. pass the collection as an array

Example method:

/**
 * <p>
 * Prints the {@link String}s passed
 * </p>
 *
 * @param item the bunch of character sequences to be printed
 */
public static void print(String... item) {
    System.out.println(String.join(" ", item));
}

You can use it like this:

public static void main(String[] args) throws IOException {
    // some example list of Strings
    List<String> words = new ArrayList<>();
    words.add("You");
    words.add("can");
    words.add("pass");
    words.add("items");
    words.add("in");
    words.add("an");
    words.add("Array");
    
    // first thing you can do is passing each item of the list to the method
    print(words.get(0), words.get(1), words.get(2), words.get(3), words.get(4), words.get(5), words.get(6));
    
    // but better pass an array, String[] here
    String[] arrWords = words.stream().toArray(String[]::new);
    print(arrWords);
}

which outputs

You can pass items in an Array
You can pass items in an Array

Upvotes: 0

Nitin Jain
Nitin Jain

Reputation: 1344

Convert the list of strings into arrays of strings.

ArrayList<String> strings = new ArrayList<>();
callMethod(strings.toArray(new String[strings.size()]));

Upvotes: 0

Related Questions