Java Program to Combine Two List by Alternatively Taking Elements
A list is an ordered sequence of elements stored together to form a collection. A list can contain duplicate as well as null entries. A list allows us to perform index-based operations, that is additions, deletions, manipulations, and positional access. Java provides an in-built interface <<java.util>> to perform list as well as other class-based functions.
Cases: There can occur two different scenarios while doing so as per the length of lists
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
- If list 2 gets exhausted while adding elements alternatively then the remaining elements of list 1 are the second list is remaining elements of list 1 to be added in the same sequence of occurrence.
- If list 1 gets exhausted and so on as discussed in the above case vice-versa
So, the Aim is to completely remove the elements from second one and add to first one list and whatever is left will be the second list.
Approach: The following approach is adopted to store elements alternatively in a merged list.
- Two lists are declared and initialized with a set of elements.
- Two counters, i and j are maintained to iterate over the length of the lists. The loop runs until the shorter length of both the lists.
- An empty list is maintained to store the merged contents of both the lists, in order of list1 followed by list2.
- At the end of the loop, one of the list, that is a shorter one is exhausted. A loop is then used to iterate over the remaining elements of the longer list and store them at the end one by one.
- The data type of the merged list should be similar to the individual lists.
Implementation: Two examples are discussed below considering both integer list and string lists
Example 1: String Lists
List1 contents: Geeks Geeks portal List2 contents: for is CSE portal Merged List contents: Geeks for Geeks is CSE portal portal
Example 2: Integer Lists
List1 contents: 2 4 6 List2 contents: 1 3 5 7 Merged List contents: 1 2 3 4 5 6 7