// this comparator imposes orderings that are inconsistent with equals. publicintcompare(String a, String b){ if (base.get(a) >= base.get(b)) { return1; } else { return -1; } // returning 0 would merge keys } } // output: // unsorted map: {A=9, B=2, C=7, D=1} // sorted map: {D=1, B=2, C=7, A=9}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// 2. add every Entry into List, sort the List and then put into LinkedHashMap publicstatic <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map){ List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
Map<K, V> result = new LinkedHashMap<>(); for (Map.Entry<K, V> entry : list) { result.put(entry.getKey(), entry.getValue()); } return result; } // test: same as 1