Learn to add multiple items to ArrayList. There can be two usescases which require to add multiple items to an arraylist.
- Add all items from a collection to arraylist
- Add selected items from a collection to arraylist
1. Add multiple items to arraylist – ArrayList.addAll()
To add all items from another collection to arraylist, use ArrayList.addAll() method.
public class ArrayListExample { public static void main(String[] args) { //List 1 List<String> namesList = Arrays.asList( "alex", "brian", "charles"); //List 2 ArrayList<String> otherList = new ArrayList<>(); //Copy all items from list 1 to list 2 otherList.addAll(namesList); System.out.println(otherList); } }
Program output.
[alex, brian, charles]
2. Add only selected items to arraylist
This method uses Java 8 stream API. We create a stream of elements from first list, add filter to get the desired elements only, and then collect filtered elements to another list.
public class ArrayListExample { public static void main(String[] args) { //List 1 List<String> namesList = Arrays.asList( "alex", "brian", "charles"); //List 2 ArrayList<String> otherList = new ArrayList<>(); //skip element with value "alex" namesList.stream() .filter(name -> !name.equals("alex")) .forEachOrdered(otherList::add); System.out.println(otherList); } }
Program output.
[brian, charles]
In above examples, we learned to all multiple elements to arraylist. We have added all element to arraylist and then we saw the example to add only selected items to the arraylist from Java 8 stream of elements.
Happy Learning !!
Read More:
A Guide to Java ArrayList
ArrayList Java Docs
zemiak
Add one value multiple to ArrayList of size n.