How to Merge Two ArrayLists in Java


In this example we will show two methods to join two ArrayLists in Java, as shown below:

JDK – List.addAll()
Apache Common – ListUtils.union()

Source Code

1)

package com.beginner.examples;

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

public class JoinListExample1 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        List al = new ArrayList();
        al.add("aa");
        al.add("bb");
        al.add("cc");
        List al2 = new ArrayList();
        al2.addAll(al);
        System.out.println("The content in al2 is:" + al2);
    }

}

Output:

The content in al2 is:[aa, bb, cc]

2)

package com.beginner.examples;

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


public class JoinListExample2 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        List al = new ArrayList();
        al.add("aa");
        List al2 = new ArrayList();
        al2.add("bb");
        List al3 = ListUtils.union(al, al2);

        System.out.println("The content in al3 is: " + al3);


    }

}
class ListUtils {
    public static ArrayList union(List l1, List l2) {
        List aList = new ArrayList();
        for (int i = 0; i < l1.size(); i++) {
            aList.add(l1.get(i));
        }
        for (int i = 0; i < l2.size(); i++) {
            aList.add(l2.get(i));
        }
        return (ArrayList) aList;
    }
}

Output:

The content in al3 is: [aa, bb]

Tips

Append Lists
To append ListB to the end of ListA, uses
listA.addAll(listB);

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments