Algorithm


  1. Input:

    • Two lists: list1 and list2 of the same type.
  2. Output:

    • A new list joinedList containing all elements from list1 and list2.
  3. Algorithm Steps:

    • Create an empty list joinedList.
    • Iterate over each element in list1.
      • Add the current element to joinedList.
    • Iterate over each element in list2.
      • Add the current element to joinedList.
  4. Result:

    • The joinedList now contains all elements from both list1 and list2.

 

Code Examples

#1 Code Example- Join Two Lists using addAll()

Code - Java Programming

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

public class JoinLists {

    public static void main(String[] args) {

        List < String> list1 = new ArrayList();
        list1.add("a");

        List < String> list2 = new ArrayList();
        list2.add("b");

        List < String> joined = new ArrayList();

        joined.addAll(list1);
        joined.addAll(list2);

        System.out.println("list1: " + list1);
        System.out.println("list2: " + list2);
        System.out.println("joined: " + joined);

    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
list1: [a]
list2: [b]
joined: [a, b]

#2 Code Example- Join Two Lists using union()

Code - Java Programming

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections.ListUtils;

public class JoinLists {

    public static void main(String[] args) {

        List < String> list1 = new ArrayList();
        list1.add("a");

        List < String> list2 = new ArrayList();
        list2.add("b");

        List < String> joined = ListUtils.union(list1, list2);

        System.out.println("list1: " + list1);
        System.out.println("list2: " + list2);
        System.out.println("joined: " + joined);

    }
}
Copy The Code & Try With Live Editor

#3 Code Example- Join Two Lists using stream

Code - Java Programming

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class JoinLists {

    public static void main(String[] args) {

        List < String> list1 = new ArrayList();
        list1.add("a");

        List < String> list2 = new ArrayList();
        list2.add("b");

        List < String> joined =  Stream.concat(list1.stream(), list2.stream())
                .collect(Collectors.toList());

        System.out.println("list1: " + list1);
        System.out.println("list2: " + list2);
        System.out.println("joined: " + joined);

    }
}
Copy The Code & Try With Live Editor
Advertisements

Demonstration


Java Programing Example to Join Two Lists-DevsEnv