sorting a hashmap who's key is another hashmap

2019-09-25 08:37发布

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?

2条回答
萌系小妹纸
2楼-- · 2019-09-25 09:22

You're better off just creating a class for a name and number of occurrences.

import java.util.Objects;

public class NameCount implements Comparable<NameCount> {

    private final String name;
    private int count;

    public NameCount(String name) {
        this.name = name;
        count = 0;
    }

    public NameCount(String name, int count) {
        this.name = name;
        this.count = count;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public void incrementCount() {
        count++;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(this.name);
    }

    @Override
    public boolean equals(Object obj) {
        if(obj == null) return false;
        if(getClass() != obj.getClass()) return false;
        final NameCount other = (NameCount)obj;
        if(!Objects.equals(this.name, other.name)) return false;
        return true;
    }

    @Override
    public int compareTo(NameCount o) {
        return o.count - count;
    }

}

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 a NameCount for it and use contains. The compareTo implementation orders from higher count to lower, so when getting the List<NameCount> for a given year, you can then use Collections.sort(list) on it and ask for the index for a NameCount with the same name.

public void test(Map<Integer, List<NameCount>> map) {

    int year = 2017;
    List<NameCount> list = map.get(year);
    // Do null-check on list first when using this...
    Collections.sort(list);
    NameCount check = new NameCount("Abigail");
    int rank = list.indexOf(check) + 1;

}

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.

查看更多
老娘就宠你
3楼-- · 2019-09-25 09:28

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()));
查看更多
登录 后发表回答