I extends a TreeMap and override entrySet() and values() methods. Key and value need to be Comparable.
Follow the code:
public class ValueSortedMap<K extends Comparable, V extends Comparable> extends TreeMap<K, V> {
@Override
public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> originalEntries = super.entrySet();
Set<Entry<K, V>> sortedEntry = new TreeSet<Entry<K, V>>(new Comparator<Entry<K, V>>() {
@Override
public int compare(Entry<K, V> entryA, Entry<K, V> 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<V> values() {
Set<V> sortedValues = new TreeSet<>(new Comparator<V>(){
@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<String, Integer> 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<String, Double> 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());
}
}