How to get the maximum value in the list <Map <String, Object >> in Java8

I am trying to get the maximum value in Java 8.

It consists 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; } 

The largest number of "A" keys will be shown here.

I tried to do the same in Java 8, but I cannot get the maximum value.

+5
source share
1 answer

If the values ​​are expected to be integers, I would change the type of 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 using getOrDefault instead of get to avoid null values:

 int max = list.stream() .mapToInt(map->map.getOrDefault("A",Integer.MIN_VALUE)) .max(); .orElse(someDefaultValue); 
+10
source

Source: https://habr.com/ru/post/1267076/


All Articles