How to convert `ArrayList<String>` into a type that can be passed into a `String…` parameter

I have a function that returns an ArrayList<String>, and I need to be able to pass the result of this function into another function with a String... parameter. The problem is, the function that takes in the String... has another string already being passed in, as showed in the example below.

public void printStrings(String... strings) {
    for (String str : strings) {
        System.out.println(str);
    }

}

public ArrayList<String> getArrayList() {
    ArrayList<String> list = new ArrayList<>();

    list.add("Hello");
    list.add("World");

    return list;
}

public static void main(String[] args) {
    // This is what needs to happen, but does not work
    printStrings("Additional String", getArrayList());
    //            ^ String already being passed in

}

This additional string should not be removed, and in the actual code the function that takes in the strings would have a lot of other strings going into it, and this function should not be changed.

Note that this is not converting an ArrayList to an String[]. That would not fix this problem.

>Solution :

There isn’t a language construct that supports this exactly. You could store the List in a variable, add the additional String to the front, then convert to an array.

var list = getArrayList();
list.add(0, "Additional String");
printStrings(list.toArray(String[]::new));

Leave a Reply