In 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 final ArrayList
.
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
Rajasekhar says
Hai Thanks for your awesome tutorial i have one small doubt regarding this joining to Lists can we join String type and Integer type together if yes please give me one small example
once again thanks for your work u made my learning easy