Java: Passing a list as argument to a vararg method

Use List.toArray(T[] arr):

yourVarargMethod(yourList.toArray(new String[0]));

(Replace String with whatever type of objects your list contains.)

Details

String... behaves similarly to String[].

You could also use new String[yourList.size()] instead of new String[0]. This is however not more performant.

Full Example

import java.util.List;
class Demo {

    public static void main(String[] args) {
        List<String> yourList = List.of("hello", "world");
        yourVarargMethod(yourList.toArray(new String[0]));
    }

    static void yourVarargMethod(String... args) {
        for (String str : args) {
            System.out.println(str);
        }
    }
}

Comments

Be the first to comment!