// 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 extendsComparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) { List<Map.Entry<K, V>> list = newLinkedList<>(map.entrySet()); Collections.sort(list, newComparator<Map.Entry<K, V>>() {