Skip to content
Related Articles
Get the best out of our app
Open App

Related Articles

Join two ArrayLists in Java

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given two ArrayLists in Java, the task is to join these ArrayLists.


Input: ArrayList1: [Geeks, For, ForGeeks], ArrayList2: [GeeksForGeeks, A computer portal]
Output: ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal]

Input: ArrayList1: [G, e, e, k, s], ArrayList2: [F, o, r, G, e, e, k, s]
Output: ArrayList: [G, e, e, k, s, F, o, r, G, e, e, k, s]

Approach: ArrayLists can be joined in Java with the help of Collection.addAll() method. This method is called by the destination ArrayList and the other ArrayList is passed as the parameter to this method. This method appends the second ArrayList to the end of the first ArrayList.



Below is the implementation of the above approach:

// Java program to demonstrate
// How to sort ArrayList in descending order
import java.util.*;
public class GFG {
    public static void main(String args[])
        // Get the ArrayList1
            list1 = new ArrayList<String>();
        // Populate the ArrayList
        // Print the ArrayList 1
        System.out.println("ArrayList 1: "
                           + list1);
        // Get the ArrayList2
            list2 = new ArrayList<String>();
        list2.add("A computer portal");
        // Print the ArrayList 2
        System.out.println("ArrayList 2: "
                           + list2);
        // Join the ArrayLists
        // using Collection.addAll() method
        // Print the joined ArrayList
        System.out.println("Joined ArrayLists: "
                           + list1);

My Personal Notes arrow_drop_up
Last Updated : 11 Dec, 2018
Like Article
Save Article
Similar Reads
Related Tutorials