Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

java-8

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.

like image 529
pamiers Avatar asked Apr 24 '17 05:04

pamiers


People also ask

How do I find the maximum element in a stream list?

Calling stream() method on the list to get a stream of values from the list. Calling mapToInt(value -> value) on the stream to get an Integer Stream. Calling max() method on the stream to get the max value. Calling orElseThrow() to throw an exception if no value is received from max()


1 Answers

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);
like image 161
Eran Avatar answered Oct 07 '22 00:10

Eran