You have a fundamental problem: you want to check the uniqueness at the same time and order records. There is no built-in collection that will check at the same time that the entries are equal and that their comparison is 0.
For example, two implementations of Set : HashSet and TreeSet :
HashSet uses Object .equals() / .hashCode() to check for equality;TreeSet uses Comparator (or the ability of Comparable objects, if they implement it) to check for equality.
This is not quite the same. In fact, with one specific JDK class, i.e. BigDecimal , this may seem rather unexpected:
final BigDecimal one = new BigDecimal("1"); final BigDecimal oneDotZero = new BigDecimal("1.0"); final Set<BigDecimal> hashSet = new HashSet<>(); // BigDecimal implements Comparable of itself, so we can use that final Set<BigDecimal> treeSet = new TreeSet<>(); hashSet.add(one); hashSet.add(oneDotZero); // hashSet size is 2: one.equals(oneDotZero) == false treeSet.add(one); treeSet.add(oneDotZero); // treeSet size is... 1! one.compareTo(oneDotZero) == 0
You cannot both drink and eat it. Here you want to check the uniqueness according to the name and comparison according to age, you should use Map .
To get a sorted list of faces, you will need to make a copy of this .values() map as a list and use Collections.sort() . If you use Guava, this last part is as simple as Ordering.natural().sortedCopy(theMap.values()) if your values implement Comparable .
source share