Skip to main content
 

Just saw this guava witchcraft snippet in a code review today from @112047346673343275962.

In this case we wanted to sort by a primary, secondary and tertiary key.  However we only want to keep the first 'primary' entry found.

The magic is that ImmutableSortedSet throws away duplicates, and you can define duplication with the orderedBy() method (which should almost be renamed to .orderedByAndEquals())

sorted = primaryOrdering.compound(secondary)
    .compound(tertiary)
    .immutableSortedCopy(full);

return ImmutableSortedSet
  .orderedBy(primary)
  .addAll(sorted).build();