25. Second Way to sort a Map By Value in Descending Order - prabhatrocks07/Core-Java-Programming GitHub Wiki

public class SortMapByValueDescending {

public static void main(String[] args) {
	Map<String, Double> map = new HashMap<String, Double>();
	ValueComparator bvc = new ValueComparator(map);
	Map<String, Double> sortedMap = new TreeMap<>(bvc);
	
	map.put("A", 99.5);
	map.put("B", 85.4);
	map.put("C", 66.4);
	map.put("D", 120.3);
	map.put("D", 50.3);
	map.put("E", 78.6);
	map.put("F", 148.5);
	
	System.out.println("Unsorted Map : " + map);
	sortedMap.putAll(map);
	System.out.println("Sorted Map : " + sortedMap);
	
}

}

class ValueComparator implements Comparator<String> {

Map<String, Double> base;

public ValueComparator(Map<String, Double> base) {
	this.base = base;
}

//Note : this comparator imposes orderings that are inconsistent with equals.
@Override
public int compare(String a, String b) {
	if(base.get(a) > base.get(b)) {
		return -1;
	} else {
		return 1; //returning 0 would merge keys
	}
}
}
⚠️ **GitHub.com Fallback** ⚠️