Using Java8 Stream to Search for Highest Map Values

I wrote the following method to find the key mapping with the highest values ​​and try to convert to java stream. Could you help me?

private List<Integer> testStreamMap(Map<Integer, Long> mapGroup) { List<Integer> listMax = new ArrayList<Integer>(); Long frequency = 0L; for (Integer key : mapGroup.keySet()) { Long occurrence = mapGroup.get(key); if (occurrence > frequency) { listMax.clear(); listMax.add(key); frequency = occurrence; } else if (occurrence == frequency) { listMax.add(key); } } return listMax; } 
+5
source share
2 answers

You can get one key through

 Integer max=mapGroup.entrySet().stream().max(Map.Entry.comparingByValue()).get().getKey(); 

but unfortunately there is no built-in function to get all equivalent maxima.

The simplest, most straightforward solution is to first find the maximum value and after that get all the key mappings:

 private List<Integer> testStreamMap(Map<Integer, Long> mapGroup) { if(mapGroup.isEmpty()) return Collections.emptyList(); long max = mapGroup.values().stream().max(Comparator.naturalOrder()).get(); return mapGroup.entrySet().stream() .filter(e -> e.getValue() == max) .map(Map.Entry::getKey) .collect(Collectors.toList()); } 

Solutions for obtaining all maximum flow values ​​in a single pass are discussed in " How to get max () to return ALL maximum values ​​in a Java thread? " You will see that single-pass solutions are much more complicated and not worth the effort if your entry is a regular Map (for example, HashMap ), which can be repeated many times several times cheaper.

+9
source

I'm not sure what half of your code is trying to do, but to answer your question according to the headline, which I assume was to "find the record with the highest value":

 Map.Entry<Integer, Long> maxEntry = map.entrySet().stream() .max(Map.Entry.comparingByValue()).get(); 
+8
source

Source: https://habr.com/ru/post/1263861/


All Articles