ArrayList add ArrayList

Learn to add multiple items to ArrayList. There can be two usescases which require to add multiple items to an arraylist.

  1. Add all items from a collection to arraylist
  2. 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 namesList = Arrays.asList[ "alex", "brian", "charles"]; //List 2 ArrayList otherList = new ArrayList[]; //Copy all items from list 1 to list 2 otherList.addAll[namesList]; System.out.println[otherList]; } }

Program output.

[alex, brian, charles]
Please note that this method copies the element references in list. So both the list refer to same objects. If we change an object in one list, same object in other list will also get changed.

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 namesList = Arrays.asList[ "alex", "brian", "charles"]; //List 2 ArrayList 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

Was this post helpful?

Let us know if you liked the post. Thats the only way we can improve.
Yes
No

Video liên quan

Chủ Đề