Write a method called alternate that accepts two Lists as its parameters and returns a new List containing alternating elements from the two lists, in the following order:
• First element from first list
• First element from second list
• Second element from first list
• Second element from second list
• Third element from first list
• Third element from second list
• . . .
If the lists do not contain the same number of elements, the remaining elements from the longer list should be placed consecutively at the end. For example, for a first list of (1, 2, 3, 4, 5) and a second list of (6, 7, 8, 9, 10, 11, 12), a call of alternate(list1, list2) should return a list containing (1, 6, 2, 7, 3, 8, 4, 9, 5, 10, 11, 12).
package collections;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Alternate {
// alternate method takes two arguments i.e, two List types
public static List<Integer> alternate(List<Integer> list1, List<Integer> list2) {
int i = 0;
int j = 0;
int sizel1 = list1.size();
int sizel2 = list2.size();
boolean flag = true;
// create a new List to store our new alternate elements
List<Integer> list = new ArrayList<Integer>();
while (i < sizel1 || j < sizel2) {
// we creted a boolean flag which sets false for one iterate and true for
// next iterate which cause read element for alternately from two lists
if (i < sizel1 && flag) {
list.add(list1.get(i));
i++;
} else if (j < sizel2 && !flag) {
list.add(list2.get(j));
j++;
}
flag = !flag;
}
// return our new list with alternate elements
return list;
}
public static void printList(List<Integer> list) {
System.out.println(Arrays.toString(list.toArray()));
}
public static void main(String[] args) {
List<Integer> list1 = new ArrayList<Integer>();
Collections.addAll(list1, 4, 8, 9, 3, 7, 12, 35, 64, 8, 24, 0, 14, 36, 45);
List<Integer> list2 = new ArrayList<Integer>();
Collections.addAll(list2, 5, 6, 7, 3, 1, 56, 8, 21, 2, 4);
// call and print the elements in the new list
System.out.println("alternate elements of list1 and list2 is: \n"+(alternate(list1, list2)));
}
}
Output:
alternate elements of list1 and list2 is:
[4, 5, 8, 6, 9, 7, 3, 3, 7, 1, 12, 56, 35, 8, 64, 21, 8, 2, 24, 4, 0, 14, 36, 45]