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

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

Output

<br />
[9, 10, 11, 1, 2, 3]<br />

Add a list at any index

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

Output

<br />
[9, 10, 11, 1, 2, 3]<br />

Like this post? Don’t forget to share it!

Leave a Reply

Your email address will not be published. Required fields are marked *

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