Java 8 stream - Find max count values for Map<String, List<Object>>

meso :

I am not so familiar with Java 8 and looking to see if I could find something equivalent of the below code using streams.

The below code mainly tries to look for the key which has max number of values across it and returns that key. I could not find much help anywhere on this format.

int max = 0;
String maxValuesString = null;
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
    if(max < entry.getValue().size()) {
        maxValuesString = entry.getKey();
        max = entry.getValue().size();
    }
}
ernest_k :

You can use max with a comparator that checks the size of the value

String maxValuesString = map.entrySet()
            .stream()
            .max(Comparator.comparingInt(entry -> entry.getValue().size()))
            .map(Map.Entry::getKey) 
            .orElse(null);

Edit: thanks to comment below by Andreas for the clean optional.map

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=86590&siteId=1