001package org.conqat.lib.commons.collections; 002 003import java.util.Comparator; 004import java.util.Iterator; 005import java.util.SortedSet; 006 007/** 008 * Comparator that creates a natural order of {@link SortedSet}s if their values 009 * of the set are {@link Comparable}. The sets are first ordered by size. If two 010 * {@link SortedSet}s have the same size, the value pairs with identical index 011 * in the set order are compared. 012 */ 013public class SortedSetsComparator<T extends Comparable<T>> implements Comparator<SortedSet<T>> { 014 015 @Override 016 public int compare(SortedSet<T> firstSet, SortedSet<T> secondSet) { 017 int result = Integer.compare(firstSet.size(), secondSet.size()); 018 019 if (result != 0) { 020 return result; 021 } 022 023 Iterator<T> secondSetIterator = secondSet.iterator(); 024 025 for (T firstSetElement : firstSet) { 026 result = firstSetElement.compareTo(secondSetIterator.next()); 027 028 if (result != 0) { 029 return result; 030 } 031 } 032 033 return 0; 034 } 035}