Learn to add multiple items to an ArrayList in a single statement using simple-to-follow Java examples.
1. Using List.of() or Arrays.asList() to Initialize a New ArrayList
To initialize an ArrayList with multiple items in a single line can be done by creating a List of items using either Arrays.asList() or List.of() methods. Both methods create an immutable List containing items passed to the factory method.
In the given example, we add two strings, “a” and “b”, to the ArrayList.
ArrayList<String> arrayList = new ArrayList<>(Arrays.asList("a", "b")); //or ArrayList<String> arrayList = new ArrayList<>(List.of("a", "b"));
2. Using Collections.addAll() to Add Items from an 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 add the whole collection into this ArrayList.
List<String> namesList = Arrays.asList( "a", "b", "c"); ArrayList<String> instance = new ArrayList<>(namesList);
3. Using Stream API to Add Only Selected Items
This method uses Java Stream API. We create a stream of elements from the first list, add a filter() to get the desired elements only, and then add the filtered elements to another list.
//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 add multiple elements to ArrayList. We have added all elements to ArrayList, and then we saw the example of adding only selected items to the ArrayList from the Java 8 stream API.
Happy Learning !!