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?
You're better off just creating a class for a name and number of occurrences.
You can then define your map as
Map<Integer, List<NameCount>>
. Note how the above class defines equality and hash code based only on the name, so if you want to see if a name is in a list, you can just create aNameCount
for it and usecontains
. ThecompareTo
implementation orders from higher count to lower, so when getting theList<NameCount>
for a given year, you can then useCollections.sort(list)
on it and ask for the index for aNameCount
with the same name.It might seem to make more sense to use
TreeSet
map values to guarantee unique name entries and keep them sorted all the time, but note that TreeSet defines equality based on comparison, not equals, and it wouldn't let you get the index.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
and make your data structure a
HashMap<Integer, TreeSet<NameFrequency>>
and define a comparator for theTreeSet
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: