Reputation: 493
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();
}
}
Upvotes: 3
Views: 2532
Reputation: 45309
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
Upvotes: 8