Tutorial

How to Merge Two Lists in Java?

Published on August 3, 2022
author

Jayant Verma

How to Merge Two Lists in Java?

Merging two lists in Java is often a useful operation. These lists can be ArrayLists or LinkedLists.

How to Merge Two Lists in Java

There are multiple ways we can merge two lists in Java. Let’s explore some of the straightforward ones to get your job done!

1. The addAll() method to merge two lists

The addAll() method is the simplest and most common way to merge two lists.

For ArrayList :

import java.util.ArrayList;

public class Main {

    public static void main(String[] args)
    {
ArrayList<Integer> l1 = new ArrayList<Integer>();
        l1.add(1);
        l1.add(3);
        l1.add(5);
ArrayList<Integer> l2 = new ArrayList<Integer>();
        l2.add(2);
        l2.add(4);
        l2.add(6);
ArrayList<Integer> merge = new ArrayList<Integer>();
        merge.addAll(l1);
        merge.addAll(l2);
System.out.println("L1 : "+l1);
System.out.println("L2 : "+l2);
System.out.println("Merged : "+merge);
}
}
Merge Arraylists Addall 1
Output

Note the order of appearance of elements matches the order in which addAll() is called.

For LinkedLists:

import java.util.LinkedList;

public class Main {

    public static void main(String[] args)
    {
LinkedList<Integer> L1 = new LinkedList<>();
        L1.add(1);
        L1.add(3);
        L1.add(5);
LinkedList<Integer> L2 = new LinkedList<>();
        L2.add(2);
        L2.add(4);
        L2.add(6);
LinkedList<Integer> merged = new LinkedList<>();
        merged.addAll(L1);
        merged.addAll(L2);

System.out.println("L1 : "+L1);
System.out.println("L2 : "+L2);
System.out.println("Merged : "+merged);
}
}
LinkedList AddAll 1
Output

2. Using iterators to merge two lists in Java

We can use an Iterator to traverse the list and merge.

For ArrayList :

import java.util.ArrayList;

public class Main {

    public static void main(String[] args)
    {
ArrayList<Integer> l1 = new ArrayList<Integer>();
        l1.add(1);
        l1.add(3);
        l1.add(5);
ArrayList<Integer> l2 = new ArrayList<Integer>();
        l2.add(2);
        l2.add(4);
        l2.add(6);

ArrayList<Integer> Itmerge = new ArrayList<>();
        Iterator i = l1.iterator();
        while (i.hasNext()) {
           Itmerge.add((int)i.next());
        }
        i=l2.iterator();
        while (i.hasNext()) {
            Itmerge.add((int)i.next());
        }
System.out.println("L1 : "+l1);
System.out.println("L2 : "+l2);
System.out.println("Merged : "+Itmerge);
}
}

Iterator first traverses the ArrayList l1 and adds all the elements to Itmerge, it then traverses the ArrayList l2 and adds all the elements to Itmerge.

Iterator Arraylist 1
Output

Another way to merge the two lists is to simply add elements from one list to the other. There is no need to create a new list unless you need to keep the existing data intact.

Iterator i = l1.iterator();
while (i.hasNext())
{
  l2.add((int)i.next());
}

System.out.println("Merged : "+l2);

In this case, all the elements are added to the list l2. This saves the memory spent in the creation of an extra list. Adding the elements of one list to another saves the extra traversal.

Single Iter Merge 1
Output

For LinkedList:

import java.util.LinkedList;

public class Main {

    public static void main(String[] args)
    {
LinkedList<Integer> L1 = new LinkedList<>();
        L1.add(1);
        L1.add(3);
        L1.add(5);
LinkedList<Integer> L2 = new LinkedList<>();
        L2.add(2);
        L2.add(4);
        L2.add(6);
LinkedList<Integer> merged = new LinkedList<>();
      
        Iterator i = L1.iterator();
        while (i.hasNext()) {
           L2.add((int)i.next());
        }
System.out.println(L2);
}
}

Linkedlist Merge iterator

3. Merge Multiple Lists using for loop

For loop is also useful to merge two lists.

For ArrayList:

import java.util.ArrayList;

public class Main {

    public static void main(String[] args)
    {
ArrayList<Integer> l1 = new ArrayList<Integer>();
        l1.add(1);
        l1.add(3);
        l1.add(5);
ArrayList<Integer> l2 = new ArrayList<Integer>();
        l2.add(2);
        l2.add(4);
        l2.add(6);
ArrayList<Integer> Itmerge = new ArrayList<>();
        for(int i=0;i<l1.size();i++){
            Itmerge.add(l1.get(i));
        }
        for(int i=0;i<l2.size();i++){
            Itmerge.add(l2.get(i));
        }
System.out.println(Itmerge);
}
}

The loop traverses both the ArrayLists and adds each element one by one to a newly created list.

Adding the elements of one list to another saves the extra traversal.

 for(int i=0;i<l2.size();i++){
      l1.add(l2.get(i));
   }
System.out.println(l1);

This for loop adds the elements of l2 to l1 one by one. In this case, l1 will contain the final list of merged elements.

Forloop Arraylist 1
Output

For LinkedList:

To understand the traversal of linked lists a little better let us define our own linked list.

This will require a class for nodes. A node needs two things, data and the address of the next node.

Code for class node :

public class node {
    int data;
    node next;
    public node(int data){
        this.data=data;
        next=null;
    }
}

Note that the next is of type node since it stores the address of a node. Creating the same two lists as used in earlier examples:

public class Main {

    public static void main(String[] args)
    {        
        node head = new node(1);
        node temp = new node(3);
        head.next=temp;
        node temp1 = new node(5);
        temp.next=temp1;
        node head2 = new node(2);
        node temp2 = new node(4);
        head2.next=temp2;
        node temp3 = new node(6);
        temp2.next=temp3;
}
}

This will create lists that look like :

Lists 1

Each arrow represents the next link. To link the two lists together we need to link the end of one list to the head of the second.

List Merge Graphic 1

This can be done as follows:

node trav=head;
while(trav.next!=null){
    trav=trav.next;
}
trav.next=head2;

A node ‘trav’ is initiated and pointed at the head of the first list. The first list is traversed until trav reaches the end of the first list.

When the end is reached, it changes the next link of the last node to head of the second list. This forms a link between the two lists.

Printing all the lists:

public class Main {

    public static void main(String[] args)
    { 
        node head = new node(1);
        node temp = new node(3);
        head.next=temp;
        node temp1 = new node(5);
        temp.next=temp1;
        node head2 = new node(2);
        node temp2 = new node(4);
        head2.next=temp2;
        node temp3 = new node(6);
        temp2.next=temp3;

//printing list 1
        System.out.println("List 1 :");
        node trav = head;

        while(trav!=null){
            System.out.print(trav.data + " ");
            trav=trav.next;
        }

        System.out.println();
//prinitng list 2
        System.out.println("List 2 :");
        trav= head2;

        while(trav!=null){
            System.out.print(trav.data + " ");
            trav=trav.next;
        }
        System.out.println();

//merging the two list

         trav=head;
        while(trav.next!=null){
            trav=trav.next;
        }
        trav.next=head2;
// printing merged list
        System.out.println("merged list :");
        trav = head;
        while(trav!=null){
            System.out.print(trav.data + " ");
            trav=trav.next;
        }
}
}
Output Forloop Lists 1
Output

Conclusion

We saw the different ways to merge two lists in Java. These are ranged from inbuilt functions to basic for loops. The last example above gives a deeper understanding of how lists work in Java. Using the approach of the last example you can have more control over the order in which elements appear in the list.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Jayant Verma

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.