Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I wrote following method to find the keys mapped to the highest values and trying to convert to java Streams. Can you please help?

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
361 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can get a single key via

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

but unfortunately, there is no built-in function for getting all equivalent maximums.

The simplest, straight-forward solution is to find the maximum value first and retrieve all keys mapping to that value afterwards:

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 getting all maximum values of a stream in a single pass, are discussed in “How to force max() to return ALL maximum values in a Java Stream?”. You will see that single-pass solutions are much more complicated and not worth the effort if your input is an ordinary Map (e.g. HashMap), which can be iterated multiple times cheaply.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...