0

I am trying to retrieve all the keys having maximum values in a hashmap. I have the following code that does it,

List<List<Long>> maxList = map.entrySet()
                .stream()
                .filter(entry -> entry.getValue() == maxCount)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());

And my map has multiple entries having the same value. But it is fetching only the last entry in the map. Any idea on why this is happening? Any help greatly appreciated!

  • Please include a [mcve]. What is the type of `maxCount`? Is it possible that you are using == on a boxed type instead of a primitive? – Misha May 03 '17 at 02:04
  • Also, what are the generic types of the `Map`? I can tell that the key is a `Long`, but I'm not sure of the value. – Jacob G. May 03 '17 at 02:05
  • @Misha You're right, I was using == on an Integer type. Could you tell me why only the last value in the map was fetched? –  May 03 '17 at 02:24
  • It’s a pure coincidence. Assuming that you retrieved `maxCount` from the `Map` before, e.g. `Collections.max(map.values())`, the result will be an object from that map, so there will be at least one object in the map for which the `==` test will succeed, but the outcome for the other objects representing the same `long` value unpredictable. It might even happen to do the intended thing occasionally… – Holger May 03 '17 at 10:00

0 Answers0