There is no easy/elegant way to sort a Map by value in its data structure.
HashMap
s are unsorted by definition.
LinkedHashMap
s are sorted by insertion order.
TreeMap
s are sorted by key.
If you really need to, you could write an algorithm which builds up you data structure using a LinkedHashMap
as the "inner" structure and make sure the largest value is inserted first.
Alternatively, you could write a small class
class NameFrequency
{
String name;
int frequency;
}
and make your data structure a HashMap<Integer, TreeSet<NameFrequency>>
and define a comparator for the TreeSet
which orders those objects the way you like.
Or, finally, you could leave your data structure as it is and only order it when accessing it:
girls.get(2015).entrySet().stream()
.sorted((entry1, entry2) -> entry2.getValue() - entry1.getValue())
.forEachOrdered(entry -> System.out.println(entry.getKey() + ": " + entry.getValue()));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…