Issue
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.
Solution
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);
Answered By - Eran
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.