Java – how to print the largest number in a map
I'm reading a map in Java I want to browse a map with different numbers and print out the three largest numbers in the map This 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); } }
Output is
12 12 12
How to change the code so that it prints as follows:
12 10 5
thank you
Solution
The problem with your code is that you iterate over the same number three times using the same conditions without resetting the maximum number found Your code basically finds the largest number and then compares each item in the map twice with a larger number Of course, it found nothing and printed out the largest number it had ever found
What you want most is:
>Get all values (not item sets) > sort values > print out the first three
In Java:
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 if you only need the first three, is a computational overhead, but it can be ignored for lists with fewer than thousands of entries