FileDocCategorySizeDatePackage
MergeCollections.javaAPI DocExample1684Mon Nov 13 12:14:32 GMT 2006collections

MergeCollections

public class MergeCollections extends Object

Fields Summary
Constructors Summary
Methods Summary
static EgetNextElement(java.util.Iterator itr)

    if (itr.hasNext()){
      E nextElement = itr.next();
      if (nextElement == null) throw new NullPointerException();
      return nextElement;
    } else {
      return null;
    }
  
public static voidmain(java.lang.String[] args)

    Collection<Task> mergedTasks =
            MergeCollections.merge(mondayTasks, tuesdayTasks);
    assert mergedTasks.toString().equals(
            "[code db, code gui, code logic, phone Mike, phone Paul]");

  
static java.util.Listmerge(java.util.Collection c1, java.util.Collection c2)

    List<T> mergedList = new ArrayList<T>();

    Iterator<? extends T> itr1 = c1.iterator();
    Iterator<? extends T> itr2 = c2.iterator();

    T c1Element = getNextElement(itr1);
    T c2Element = getNextElement(itr2);

    // each iteration will take a task from one of the iterators;
    // continue until neither iterator has any further tasks
    while (c1Element != null || c2Element != null) {

      // use the current c1 element if either the current c2
      // element is null, or both are non-null and the c1 element
      // precedes the c2 element in the natural order
      boolean useC1Element = c2Element == null ||
              c1Element != null && c1Element.compareTo(c2Element) < 0;

      if (useC1Element) {
        mergedList.add(c1Element);
        c1Element = getNextElement(itr1);
      } else {
        mergedList.add(c2Element);
        c2Element = getNextElement(itr2);
      }
    }
    return mergedList;