I need to merge two lists alternating by N elements from each list: taking first N elements from first list, after taking first N elements from second list, after that second portion of N elements from first list, second portion of N elements from second list and so on. If one list is longer than the other, then append the remaining elements from the longer list into resulting list.
For example, first list: 1, 2, 3, 4
,
second list: 10, 11, 12, 13, 14, 15, 16, 17
merging result of alternating by N = 2
is 1, 2, 10, 11, 3, 4, 12, 13, 14, 15, 16, 17
.
Such merging could be implemented in the following way:
List<Integer> list1 = Arrays.asList(1, 2, 3, 4);
List<Integer> list2 = Arrays.asList(10, 11, 12, 13, 14, 15, 16, 17);
int alternatingNumber = 2;
List<Integer> mergedList = alternatingMerge(list1, list2, alternatingNumber);
public static <T> List<T> alternatingMerge(List<T> list1, List<T> list2, int alternatingNumber) {
List<T> result = new ArrayList<T>();
int size = Math.max(list1.size(), list2.size());
for (int outerIndex = 0; outerIndex < size; outerIndex += alternatingNumber) {
for (int innerIndex = 0; innerIndex < alternatingNumber; innerIndex++) {
if (outerIndex + innerIndex < list1.size()) result.add(list1.get(outerIndex + innerIndex));
}
for (int innerIndex = 0; innerIndex < alternatingNumber; innerIndex++) {
if (outerIndex + innerIndex < list2.size()) result.add(list2.get(outerIndex + innerIndex));
}
}
return result;
}
Similar merging algorithms for alternating by 1 element (alternatingNumber = 1) described here, but I need to implement a universal logic for any alternating number.
Is it possible to do that somehow with Stream API?