Organizational Research By

Surprising Reserch Topic

How to join/combine two ArrayLists in java


n this tutorial we will see how to join (or Combine) two ArrayLists in Java. We will be using addAll() method to add both the ArrayLists in one finalArrayList.

Example:

In this example we are merging two ArrayLists in one single ArrayList and then displaying the elements of final List.

package beginnersbook.com;
import java.util.ArrayList;
public class Details
{
    public static void main(String [] args)
    {
        //First ArrayList
        ArrayList<String> arraylist1=new ArrayList<String>();
        arraylist1.add("AL1: E1");
        arraylist1.add("AL1: E2");
        arraylist1.add("AL1: E3");

        //Second ArrayList
        ArrayList<String> arraylist2=new ArrayList<String>();
        arraylist2.add("AL2: E1");
        arraylist2.add("AL2: E2");
        arraylist2.add("AL2: E3");

        //New ArrayList
        ArrayList<String> al= new ArrayList<String>();
        al.addAll(arraylist1);
        al.addAll(arraylist2);

        //Displaying elements of the joined ArrayList
        for(String temp: al){
            System.out.println(temp);
        }
    }
}

Output:

AL1: E1
AL1: E2
AL1: E3
AL2: E1
AL2: E2
AL2: E3
asked Jun 11, 2015 in Core java by rajesh
0 votes
112 views



Related Hot Questions



Government Jobs Opening


...