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.
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()
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With