Java 8 stream conditional check

Java Programmer :
List<Map<String,Object>> list= new List<Map<String,Object>>();
System.out.println(list.stream().mapToInt(i ->  (Integer)i.get("amount")).sum());

I have a List of items like above. I am trying to print the sum of amount which would be an key inside the map. This works fine. But i am just wondering if there is way if i can just check if the map contains that key in this one line code. Any way to include an if condition of map.containsKey here?

Naman :

You are probably looking for getOrDefault to be used as:

list.stream().mapToInt(i ->  (Integer)i.getOrDefault("amount", 0)).sum());

which when the key doesn't exist returns 0 as the default value.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=113523&siteId=1