Reputation: 355
I'm trying to get max value in Java 8.
It consist of List<Map<String,Object>>
.
Before Java 8 :
int max = 0;
for(Map<String, Object> map : list) {
int tmp = map.get("A");
if(tmp>max)
max=tmp;
}
This will show the largest number of key "A".
I tried to do the same in Java 8, but I can't get the max value.
Upvotes: 6
Views: 4784
Reputation: 11
int max = listMap.stream()
.flatMap(c -> c.entrySet().stream())
.max(Comparator.comparing(Map.Entry::getValue)).get().getValue();
Upvotes: 1
Reputation: 393781
If the values are expected to be integer, I'd change the type of the Map
to Map<String,Integer>
:
List<Map<String,Integer>> list;
Then you can find the maximum with:
int max = list.stream()
.map(map->map.get("A"))
.filter(Objects::nonNull)
.mapToInt(Integer::intValue)
.max()
.orElse(someDefaultValue);
You can make it shorter by using getOrDefault
instead of get
to avoid null
values:
int max = list.stream()
.mapToInt(map->map.getOrDefault("A",Integer.MIN_VALUE))
.max();
.orElse(someDefaultValue);
Upvotes: 10