Add multiple items to ArrayList in Java

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<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]
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<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

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

1 thought on “Add multiple items to ArrayList in Java”

  1. Add one value multiple to ArrayList of size n.

     
    import java.util.*;
    public class Program {
    	public static void main(String[] args) {
    
    		var result = new ArrayList<Integer>(Arrays.asList( new Integer[10] ));
                    Collections.fill(result, 10);
    
                    System.out.println( result );
    }	}
    
    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.