Java tutorial
//package com.java2s; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.SortedSet; public class Main { public static boolean containsAll(Collection a, Collection b) { // fast paths if (a == b) return true; if (b.size() == 0) return true; if (a.size() < b.size()) return false; if (a instanceof SortedSet && b instanceof SortedSet) { SortedSet aa = (SortedSet) a; SortedSet bb = (SortedSet) b; Comparator bbc = bb.comparator(); Comparator aac = aa.comparator(); if (bbc == null && aac == null) { Iterator ai = aa.iterator(); Iterator bi = bb.iterator(); Comparable ao = (Comparable) ai.next(); // these are ok, since the sizes are != 0 Comparable bo = (Comparable) bi.next(); while (true) { int rel = ao.compareTo(bo); if (rel == 0) { if (!bi.hasNext()) return true; if (!ai.hasNext()) return false; bo = (Comparable) bi.next(); ao = (Comparable) ai.next(); } else if (rel < 0) { if (!ai.hasNext()) return false; ao = (Comparable) ai.next(); } else { return false; } } } else if (bbc.equals(aac)) { Iterator ai = aa.iterator(); Iterator bi = bb.iterator(); Object ao = ai.next(); // these are ok, since the sizes are != 0 Object bo = bi.next(); while (true) { int rel = aac.compare(ao, bo); if (rel == 0) { if (!bi.hasNext()) return true; if (!ai.hasNext()) return false; bo = bi.next(); ao = ai.next(); } else if (rel < 0) { if (!ai.hasNext()) return false; ao = ai.next(); } else { return false; } } } } return a.containsAll(b); } /** * Get the size of an iterator (number of items in it). * @param source * @return */ public static int size(Iterator source) { int result = 0; while (source.hasNext()) { source.next(); ++result; } return result; } }