I extends a TreeMap and override entrySet() and values() methods. Key and value need to be Comparable.
Follow the code:
public class ValueSortedMap extends TreeMap {
@Override
public Set> entrySet() {
Set> originalEntries = super.entrySet();
Set> sortedEntry = new TreeSet>(new Comparator>() {
@Override
public int compare(Entry entryA, Entry entryB) {
int compareTo = entryA.getValue().compareTo(entryB.getValue());
if(compareTo == 0) {
compareTo = entryA.getKey().compareTo(entryB.getKey());
}
return compareTo;
}
});
sortedEntry.addAll(originalEntries);
return sortedEntry;
}
@Override
public Collection values() {
Set sortedValues = new TreeSet<>(new Comparator(){
@Override
public int compare(V vA, V vB) {
return vA.compareTo(vB);
}
});
sortedValues.addAll(super.values());
return sortedValues;
}
}
Unit Tests:
public class ValueSortedMapTest {
@Test
public void basicTest() {
Map sortedMap = new ValueSortedMap<>();
sortedMap.put("A",3);
sortedMap.put("B",1);
sortedMap.put("C",2);
Assert.assertEquals("{B=1, C=2, A=3}", sortedMap.toString());
}
@Test
public void repeatedValues() {
Map sortedMap = new ValueSortedMap<>();
sortedMap.put("D",67.3);
sortedMap.put("A",99.5);
sortedMap.put("B",67.4);
sortedMap.put("C",67.4);
Assert.assertEquals("{D=67.3, B=67.4, C=67.4, A=99.5}", sortedMap.toString());
}
}