Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

java - sorting a hashmap who's key is another hashmap

so this is my hashmap

   public HashMap<Integer, HashMap<String, Integer>> girls =  
          new HashMap<Integer, HashMap<String, **Integer**>>();;

I want to sort the bolded by value. For clarification the outer hashMaps key stands for a year a girl child was born and the inner hashmap stands for a name mapped to the popularity ranking of the name.

So let's say that in 2015, the name Abigail was given to 47373 babies and it was the most popular name in that year, I'd want to return the number 1 bc it's the number one name. Is there any way to sort a hashmap in this way?

how would I turn the inner hashmaps values into an arraylist that I could then easily sort? Any help?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no easy/elegant way to sort a Map by value in its data structure.

  • HashMaps are unsorted by definition.
  • LinkedHashMaps are sorted by insertion order.
  • TreeMaps 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()));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...