Java Collection How to - Get keys with the biggest values from a hashmap








Question

We would like to know how to get keys with the biggest values from a hashmap.

Answer

import java.util.Set;
import java.util.TreeSet;
//from   w ww. j  ava  2s  .  c  o m
public class Main{
  public static void main(String[] args) {
    Set<Counter> set = new TreeSet<Counter>();

    set.add(new Counter("A", 1));
    set.add(new Counter("B", 5));
    set.add(new Counter("C", 10));
    set.add(new Counter("D", 4));
    set.add(new Counter("E", 3));
    set.add(new Counter("F", 5));
    set.add(new Counter("G", 15));
    set.add(new Counter("H", 225));
    set.add(new Counter("I", 225));
    for (Counter f : set) {
      System.out.println(f);
    }
  }
} 

class Counter implements Comparable<Counter> {
  private String name;
  private int freq;

  public Counter(String name, int freq) {
    this.name = name;
    this.freq = freq;
  }
  @Override
  public boolean equals(Object o) {
    if (o == null) return false;
    if (o.getClass().isAssignableFrom(Counter.class)) {
      Counter other = (Counter)o;
      return other.freq == this.freq && other.name.equals(this.name);
    } else {
      return false;
    }
  }

  @Override
  public int compareTo(Counter other) {
    if (freq == other.freq) {
      return name.compareTo(other.name);
    } else {
      return freq - other.freq;
    }
  }
  @Override
  public String toString() {
    return name + ":" + freq;
  }
}

The code above generates the following result.