How to get max value in List<Map<String, Object>> at Java8

pamiers :

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.

Eran :

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);

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=467709&siteId=1