How to Insert All Elements of Other List into ArrayList in Java


In this example, we will learn how to insert all elements of other list object to the specified index of an ArrayList object with addAll method in Java.

Source Code

package com.beginner.examples;

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

public class InsertCollectionToArraylist {

	
	public static void main(String[] args) {
		
		ArrayList al = new ArrayList();
		
		al.add("a");
		al.add("f");
		
		List list = new ArrayList();
		
		list.add("b");
		list.add("c");
		list.add("d");
		list.add("e");
		/*
		 * Add the elements of the list object to the index of the al object at 1
		 */
		al.addAll(1, list);
		
		System.out.println("Add after:"+al);
		
		

	}

}

Output:

Add after:[a, b, c, d, e, f]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments