Learn to add multiple items to an ArrayList in a single statement using simple to follow Java examples.
1. Arrays.asList() – Initializing with Multiple Items
To initialize an ArrayList with multiple items in a single line can be done by creating a List of items using Arrays.asList(), and passing the List to the ArrayList constructor.
In the given example, we are adding two strings “a” and “b” to the ArrayList.
ArrayList<String> arrayList = new ArrayList<>(Arrays.asList("a", "b"));
2. Collections.addAll() – Add Multiple Items to Existing ArrayList
To add all items from another collection to this ArrayList, we can use Collections.addAll() method that adds all of the specified items to the given list. Note that the items to be added may be specified individually or as an array.
ArrayList<String> arrayList = new ArrayList<>(Arrays.asList("a", "b")); Collections.addAll(arrayList, "c", "d"); System.out.println(arrayList); //[a, b, c, d]
Alternatively, we can use ArrayList constructor that accepts a collection and initializes the ArrayList with the items from the argument collection. This can be useful if we are adding the whole collection into this ArrayList.
List<String> namesList = Arrays.asList( "a", "b", "c"); ArrayList<String> instance = new ArrayList<>(namesList);
3. Stream API – Adding Selected Items to ArrayList
//List 1 List<String> namesList = Arrays.asList( "a", "b", "c"); //List 2 ArrayList<String> otherList = new ArrayList<>(Arrays.asList( "d", "e")); //Do not add 'a' to the new list namesList.stream() .filter(name -> !"a".equals(name)) .forEachOrdered(otherList::add); System.out.println(otherList); //[d, e, b, c]
In the above examples, we learned to all multiple elements to ArrayList. We have added all elements to ArrayList and then we saw the example to add only selected items to the ArrayList from the Java 8 stream API.
Happy Learning !!