Algorithm


1. Start
2. Create two lists (list1 and list2) to be merged.
3. Create a new list (resultList) to store the merged elements.
4. Initialize two pointers (index1 and index2) to the beginning of list1 and list2 respectively.
5. Repeat the following steps until both lists are completely traversed:
   a. If element at index1 in list1 is less than or equal to the element at index2 in list2,
      i.   Add the element at index1 to resultList.
      ii.  Increment index1.
   b. If element at index2 in list2 is less than the element at index1 in list1,
      i.   Add the element at index2 to resultList.
      ii.  Increment index2.
6. If there are remaining elements in list1, add them to resultList.
7. If there are remaining elements in list2, add them to resultList.
8. Display or return the merged resultList.
9. End

Code Examples

#1 Code Example- Merge two lists using addAll()

Code - Java Programming

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

class Main {
  public static void main(String[] args) {

    // create first list
    List < Integer> prime = new ArrayList<>();
    prime.add(2);
    prime.add(3);
    prime.add(5);
    System.out.println("First List: " + prime);

    // create second list
    List < Integer> even = new ArrayList<>();
    even.add(4);
    even.add(6);
    System.out.println("Second List: " + even);

    // create merged list
    List < Integer> numbers = new ArrayList<>();
    numbers.addAll(prime);
    numbers.addAll(even);

    System.out.println("Merged List: " + numbers);

  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
First List: [2, 3, 5]
Second List: [4, 6]
Merged List: [2, 3, 5, 4, 6]

#2 Code Example- Merge two lists using the Stream class

Code - Java Programming

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

class Main {
  public static void main(String[] args) {

    // create first list
    // asList() converts the array into the arraylist
    List < Integer> prime = new ArrayList<>(Arrays.asList(2, 3, 5));
    System.out.println("First List: " + prime);

    // create second list
    List < Integer> even = new ArrayList<>(Arrays.asList(4, 6));
    System.out.println("Second List: " + even);

    // convert both lists into stream
    Stream < Integer> list1 = prime.stream();
    Stream list2 = even.stream();

    // merge two streams
    Stream < Integer> merged = Stream.concat(list1, list2);

    // convert the merged stream into list
    List numbers = merged.collect(Collectors.toList());

    System.out.println("Merged List: " + numbers);

  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
First List: [2, 3, 5]
Second List: [4, 6]
Merged List: [2, 3, 5, 4, 6]
Advertisements

Demonstration


Java Programing to Merge two lists-DevsEnv