I have a hashmap which is the following:
HashMap<String, Integer> hm = new HashMap<String, Integer>;
hm.put("a", 1);
hm.put("b", 12);
hm.put("c", 53);
hm.put("d", 2);
hm.put("e", 17);
hm.put("f", 8);
hm.put("g", 8);
How would I get the keys which have the 3 highest values? So it would return:
"c", "e", "b"
Thanks.
My solution, sort by values and get top 3 and return key list.
List<String> keys = hm.entrySet().stream().sorted(Map.Entry.<String, Integer>comparingByValue().reversed()).limit(3).map(Map.Entry::getKey).collect(Collectors.toList());
Hope it helps