Get the keys with the biggest values from a hashmap?

后端 未结 8 1730
时光取名叫无心
时光取名叫无心 2020-12-06 02:01

I have a HashMap defined like this...

HashMap uniqueNames = new HashMap();

It stor

8条回答
  •  心在旅途
    2020-12-06 02:30

    Seems like you want something a bit like a SortedMap but one sorted on the value, not the key. I don't think such a thing exists in the standard API.

    It might be better to create a Frequency class and store instances in a SortedSet instead.

    import java.util.Set;
    import java.util.TreeSet;
    
    public class Frequency implements Comparable {
    
      private String name;
      private int freq;
    
      public Frequency(String name, int freq) {
        this.name = name;
        this.freq = freq;
      }
    
      public static void main(String[] args) {
        Set set = new TreeSet();
    
        set.add(new Frequency("fred", 1));
        set.add(new Frequency("bob", 5));
        set.add(new Frequency("jim", 10));
        set.add(new Frequency("bert", 4));
        set.add(new Frequency("art", 3));
        set.add(new Frequency("homer", 5));
    
        for (Frequency f : set) {
          System.out.println(f);
        }
      }
    
      @Override
      public boolean equals(Object o) {
        if (o == null) return false;
        if (o.getClass().isAssignableFrom(Frequency.class)) {
          Frequency other = (Frequency)o;
          return other.freq == this.freq && other.name.equals(this.name);
        } else {
          return false;
        }
      }
    
      @Override
      public int compareTo(Frequency other) {
        if (freq == other.freq) {
          return name.compareTo(other.name);
        } else {
          return freq - other.freq;
        }
      }
    
      @Override
      public String toString() {
        return name + ":" + freq;
      }
    
    }
    

    Output:

    fred:1
    art:3
    bert:4
    bob:5
    homer:5
    jim:10

提交回复
热议问题