Write a method that merges two array lists, alternating elements from both array lists
Iterators seem to do the trick most easily
public static <T> ArrayList<T> merge(Collection<T> a, Collection<T> b) {
Iterator<T> itA = a.iterator();
Iterator<T> itB = b.iterator();
ArrayList<T> result = new ArrayList<T>();
while (itA.hasNext() || itB.hasNext()) {
if (itA.hasNext()) result.add(itA.next());
if (itB.hasNext()) result.add(itB.next());
}
return result;
}
Without iterators:
public static <T> ArrayList<T> merge(List<T> a, List<T> b) {
ArrayList<T> result = new ArrayList<T>();
int size = Math.max(a.size(), b.size());
for (int i = 0; i < size; i++) {
if (i < a.size()) result.add(a.get(i));
if (i < b.size()) result.add(b.get(i));
}
return result;
}
Note, I've relaxed the method signature a bit. If you're implementing the merging using iterators, Collection
(or even Iterable
) will do. Otherwise, List
will do. There is no need to require ArrayList
as a method argument type
Without Iterator:
public static ArrayList merge(ArrayList a, ArrayList b) {
int c1 = 0, c2 = 0;
ArrayList<Integer> res = new ArrayList<Integer>();
while(c1 < a.size() || c2 < b.size()) {
if(c1 < a.size())
res.add((Integer) a.get(c1++));
if(c2 < b.size())
res.add((Integer) b.get(c2++));
}
return res;
}
Try this:I implemented using Array.
public static void main(String[] args) {
int[] first = { 1, 4, 9, 16 };
int[] second = { 9, 7, 4, 9, 11 };
int[] merge = new int[first.length + second.length];
int j = 0, k = 0, l = 0;
int max = Math.max(first.length, second.length);
for (int i = 0; i < max; i++) {
if (j < first.length)
merge[l++] = first[j++];
if (k < second.length)
merge[l++] = second[k++];
}
System.out.println(Arrays.toString(merge));
}
Output:
[1, 9, 4, 7, 9, 4, 16, 9, 11]