Joe Joe - 1 month ago 5
Java Question

How to print out the biggest numbers in a map

I was reading about maps in java. I want to go through a map of different numbers and print out the biggest 3 numbers in the map. Here is my code :

public class Test {

private static int number=0;

public static void main(String[] args) {

Map<String,Integer> m = new HashMap<String,Integer>();

m.put("haha", 1);
m.put("aa", 2);
m.put("rewq", 3);
m.put("la", 12);
m.put("oia", 10);
m.put("uyta", 4);
m.put("jpa", 5);


for (Entry<String, Integer> e : m.entrySet()) {

if (e.getValue() > number) {
number = e.getValue();
}

}
m.values().remove(number);
System.out.println(number);

for (Entry<String, Integer> e : m.entrySet()) {

if (e.getValue() > number) {
number = e.getValue();
}

}
m.values().remove(number);
System.out.println(number);


for (Entry<String, Integer> e : m.entrySet()) {

if (e.getValue() > number) {
number = e.getValue();
}

}
m.values().remove(number);
System.out.println(number);

}

}


The output is

12
12
12


How can I change the code to make it printing like this :

12
10
5


Thanks

Answer

The problem with your code is that you're iterating three times over the same numbers with the same condition without resetting the maximal found number. Your code basically finds the biggest number and then compares every item in the map for a bigger number two times. Of course that finds nothing and prints the previously found biggest number.

What you rather want is:

  • get all values (not entry sets)
  • sort the values
  • print out the first three

In Java that's:

ArrayList<Integer> values = new ArrayList<Integer>(m.values());
Collections.sort(values);
// turn ascending to descending
Collections.reverse(values);
System.out.println(String.format("%d, %d, %d", values.get(0), values.get(1), values.get(2)))

Sorting all values even though you only need the first three is some calculation overhead, but for lists of less than thousands of entries it's neglectible.