How to add a List to another List in Java

Collection class in java.util provides addAll method which accepts a list and adds them to the source object. Since, List and ArrayList inherit from Collection, we can use this method to add a List to another List.

boolean Collection.addAll(Collection)

This method appends all the elements from the new collection to the end of the source object list. If list changes with this operation addAll method will return true.

package com.techstackjournal;

import java.util.ArrayList;
import java.util.List;

public class AddList {

	public static void main(String[] args) {

		List<String> list1 = new ArrayList<>();
		list1.add("Java");
		list1.add("Node.js");
		list1.add("Python");
		
		List<String> list2 = new ArrayList<>();
		list2.add("Oracle");
		list2.add("MySQL");
		list2.add("MongoDB");
		
		list1.addAll(list2);

		for (String string : list1) {
			System.out.println(string);
		}

	}

}

Output:

Java
Node.js
Python
Oracle
MySQL
MongoDB

boolean Collection.addAll(index, Collection)

Using this variant of addAll method, you can insert elements from target Collection object at specified position in the source list. The rest of the elements in the source object will be shifted below to the new elements.

package com.techstackjournal;

import java.util.ArrayList;
import java.util.List;

public class AddList {

	public static void main(String[] args) {

		List<String> list1 = new ArrayList<>();
		list1.add("Java");
		list1.add("Node.js");
		list1.add("Python");
		
		List<String> list2 = new ArrayList<>();
		list2.add("Oracle");
		list2.add("MySQL");
		list2.add("MongoDB");
		
		list1.addAll(0, list2);

		for (String string : list1) {
			System.out.println(string);
		}

	}

}

Output:

Oracle
MySQL
MongoDB
Java
Node.js
Python

Leave a Comment