TSets { @SuppressWarnings("unchecked") private static <T> Set<T> sortedIntersection(SortedSet<T> a, SortedSet<T> b) { Set<T> intersection = Sets.newLinkedHashSet(); if(a.isEmpty() || b.isEmpty()) { return intersection; } Iterator<T> ait = a.iterator(); Iterator<T> bit = b.iterator(); Comparator<? super T> comp = a.comparator(); boolean ago = true; boolean bgo = true; T aelt = null; T belt = null; while (((ago && ait.hasNext()) || !ago) && ((bgo && bit.hasNext()) || !bgo)) { aelt = ago ? ait.next() : aelt; belt = bgo ? bit.next() : belt; int order = comp == null ? ((Comparable<T>) aelt).compareTo(belt) : comp.compare(aelt, belt); if(order == 0) { intersection.add(aelt); ago = true; bgo = true; } else if(order > 0) { bgo = true; ago = false; } else { ago = true; bgo = false; } } return intersection; }  static Set<T> intersection(Set<T> a, Set<T> b); static Set<Long> sequence(long from, long to); static Set<T> union(Set<T> a, Set<T> b);  }
@Test public void testSortedIntersection() { Set<Integer> a = Sets.newTreeSet(); Set<Integer> b = Sets.newTreeSet(); populate(a); populate(b); Assert.assertEquals(TSets.intersection(a, b), Sets.intersection(a, b).copyInto(Sets.<Integer> newHashSet())); }