Add elements of List to another List at a specific index

To add a list to another list at a specific location, here is the code

Add a list at the beginning
public static void main(String[] args) {
	// to make it modifiable using new
	List<Integer> list1 = new ArrayList<>(Arrays.asList(1,2, 3));
	List<Integer> list2 = Arrays.asList(9,10, 11);
	List<Integer> list3 = new ArrayList<>(list1);
	list1.clear();
	list1.addAll(list2);
	list1.addAll(list3);
	System.out.println(list1);
}

Output

[9, 10, 11, 1, 2, 3]
Add a list at any index
	
public static void main(String[] args) {
	// to make it modifiable using new
	List<Integer> list1 = new ArrayList<>(Arrays.asList(1,2, 3));
	List<Integer> list2 = Arrays.asList(9,10, 11);
	Collections.reverse(list2);
	for(Integer each:list2){
		list1.add(0, each);
	}
	// reverse it back
	Collections.reverse(list2);
	System.out.println(list1);
		
}

Output

[9, 10, 11, 1, 2, 3]

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.