Java Program to Combine Two List by Alternatively Taking Elements


Introduction

The Java program to combine two lists by alternatively taking elements is a simple code snippet that takes in two lists of any type of object that can be stored in a list and returns a new list that contains elements from both input lists alternately.

The program defines a method called alternateMerge that takes two lists as input and returns a new list that contains elements from both lists alternately. It determines the size of both lists and loops through the larger of the two lists. For each index in the loop, it adds the element from the first list at that index to the result list if the index is less than the size of the first list, and it adds the element from the second list at that index to the result list if the index is less than the size of the second list. Finally, it returns the result list.

Cases

there are two different scenarios that can occur while combining two lists by alternatively taking elements based on the length of the lists −

  • Lists of Equal Length: If both input lists are of equal length, then the program will loop through either of the two lists and add each element alternately to the result list until both lists are fully traversed. The resulting list will contain all elements from both input lists in an alternating manner.

  • Lists of Unequal Length: If the input lists are of unequal length, the program will loop through the larger of the two lists and add each element alternately to the result list until the smaller list is fully traversed. After the smaller list is fully traversed, the program will continue to loop through the remaining elements in the larger list and add them to the result list until it is fully traversed. The resulting list will contain all elements from both input lists in an alternating manner, with any remaining elements from the larger list added at the end of the result list.

In both cases, the resulting list will contain all elements from both input lists in an alternating manner, but the specific process for achieving this result will differ based on the lengths of the input lists.

Example 1: Integer Lists

Approach

  • Define a method called alternateMerge that takes two lists list1 and list2 as input and returns a new list that contains elements from both lists alternately.

  • Create an empty list called result to store the combined elements.

  • Determine the size of list1 and list2 using the size() method.

  • Determine the maximum size of the two lists using the Math.max() method.

  • Loop through the range of 0 to maxSize - 1 using a for loop.

  • For each index i in the loop, add the element from list1 at index i to result if i is less than the size of list1.

  • Similarly, add the element from list2 at index i to result if i is less than the size of list2.

  • Return the combined list result.

  • In the main method, create two lists list1 and list2 of the same data type.

  • Add elements to both lists using the add() method.

  • Call the alternateMerge method with list1 and list2 as arguments to combine the two lists.

  • Print the resulting list.

Here's a Java program that combines two lists by alternatively taking elements −

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

public class CombineLists {
   public static <T> List<T> alternateMerge(List<T> list1, List<T> list2) {
      List<T> result = new ArrayList<>();
      int size1 = list1.size();
      int size2 = list2.size();
      int maxSize = Math.max(size1, size2);
      for (int i = 0; i < maxSize; i++) {
         if (i < size1) {
            result.add(list1.get(i));
         }
         if (i < size2) {
            result.add(list2.get(i));
         }
      }
      return result;
   }

   public static void main(String[] args) {
      List<Integer> list1 = new ArrayList<>();
      list1.add(1);
      list1.add(2);
      list1.add(3);

      List<Integer> list2 = new ArrayList<>();
      list2.add(4);
      list2.add(5);
      list2.add(6);
      list2.add(7);

      List<Integer> result = alternateMerge(list1, list2);
      System.out.println(result); 
   }
}

Explanation

The alternateMerge method takes in two lists list1 and list2 and returns a new list that contains elements from both lists alternately. We first determine the size of the two lists and then iterate through the larger of the two. For each index, we add the element from list1 if it exists and then add the element from list2 if it exists. Finally, we return the combined list.

In the main method, we create two lists of integers and then call the alternateMerge method to combine them. The output should be [1, 4, 2, 5, 3, 6, 7], which is the result of alternating the elements of the two lists.

Output

[1, 4, 2, 5, 3, 6, 7]

Example 2: String Lists

Approach

  • Define a method called alternateMerge that takes two lists list1 and list2 as input and returns a new list that contains elements from both lists alternately.

  • Create an empty list called result to store the combined elements.

  • Determine the size of list1 and list2 using the size() method.

  • Determine the maximum size of the two lists using the Math.max() method.

  • Loop through the range of 0 to maxSize - 1 using a for loop.

  • For each index i in the loop, add the element from list1 at index i to result if i is less than the size of list1.

  • Similarly, add the element from list2 at index i to result if i is less than the size of list2.

  • Return the combined list result.

  • In the main method, create two lists list1 and list2 of strings.

  • Add strings to both lists using the add() method.

  • Call the alternateMerge method with list1 and list2 as arguments to combine the two lists.

  • Print the resulting list.

The above code can also be used to combine two lists of strings. Here's an example −

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

public class CombineLists {
   public static <T> List<T> alternateMerge(List<T> list1, List<T> list2) {
      List<T> result = new ArrayList<>();
      int size1 = list1.size();
      int size2 = list2.size();
      int maxSize = Math.max(size1, size2);
      for (int i = 0; i < maxSize; i++) {
         if (i < size1) {
            result.add(list1.get(i));
         }
         if (i < size2) {
            result.add(list2.get(i));
         }
      }
      return result;
   }
   public static void main(String[] args) {
      List<String> list1 = new ArrayList<>();
      list1.add("hello");
      list1.add("world");
      List<String> list2 = new ArrayList<>();
      list2.add("goodbye");
      list2.add("moon");
      List<String> result = alternateMerge(list1, list2);
      System.out.println(result); // Output: [hello, goodbye, world, moon]
   }
}

Explanation

In this example, we create two lists of strings (list1 and list2) and call the alternateMerge method to combine them. The output should be [hello, goodbye, world, moon], which is the result of alternating the elements of the two lists.

Output

[hello, goodbye, world, moon]

Conclusion

  • The Java program to combine two lists by alternatively taking elements is a useful utility for combining two separate lists of data in a specific order. The program determines the size of both input lists, loops through the larger of the two lists, and adds each element alternately to the result list until both input lists are fully traversed. The resulting list will contain all elements from both input lists in an alternating manner.

  • The program can be easily modified to combine two lists of any type of object that can be stored in a list, including strings, integers, and custom objects. Additionally, the program can handle lists of equal and unequal length, with the specific process for achieving the desired result differing based on the lengths of the input lists.

Updated on: 10-Apr-2023

754 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements