How to declare an ArrayList with values?

alvas picture alvas · Feb 11, 2014 · Viewed 464.9k times · Source

ArrayList or List declaration in Java has questioned and answered how to declare an empty ArrayList but how do I declare an ArrayList with values?

I've tried the following but it returns a syntax error:

import java.io.IOException;
import java.util.ArrayList;

public class test {
    public static void main(String[] args) throws IOException {
        ArrayList<String> x = new ArrayList<String>();
        x = ['xyz', 'abc'];
    }
}

Answer

Maroun picture Maroun · Feb 11, 2014

In Java 9+ you can do:

var x = List.of("xyz", "abc");
// 'var' works only for local variables

Java 8 using Stream:

Stream.of("xyz", "abc").collect(Collectors.toList());

And of course, you can create a new object using the constructor that accepts a Collection:

List<String> x = new ArrayList<>(Arrays.asList("xyz", "abc"));

Tip: The docs contains very useful information that usually contains the answer you're looking for. For example, here are the constructors of the ArrayList class: