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

Leave a Comment