Reputation: 1471
I have a list of Customer
objects
class Customer {
//Other properties
Map<String, Object> additionalData;
}
When I got a List<Customer> customers
, I want to sum a key called transactions
in additionalData
. How can I do that with java 8 streams?
Upvotes: 4
Views: 2342
Reputation: 393841
You can map each element of your list to the value of the "transactions" key in the corresponding map, and then sum these values:
int sum = customers.stream()
.map(c->(Integer)c.additionalData.get("transactions"))
.filter(Objects::nonNull)
.mapToInt (Integer::intValue)
.sum();
For example:
Customer c1 = new Customer();
c1.additionalData = new LinkedHashMap<> ();
c1.additionalData.put ("transactions", 14);
Customer c2 = new Customer();
c2.additionalData = new LinkedHashMap<> ();
c2.additionalData.put ("transactions", 7);
Customer c3 = new Customer();
c3.additionalData = new LinkedHashMap<> ();
List<Customer> customers = Arrays.asList (c1,c2,c3);
int sum = customers.stream()
.map(c->(Integer)c.additionalData.get("transactions"))
.filter(Objects::nonNull)
.mapToInt (Integer::intValue)
.sum();
System.out.println ("sum is " + sum);
Output:
sum is 21
This code is assuming the additionalData
member is never null
, and the value of the "transactions"
key (if it exists in the Map
) is always an Integer
. If these assumptions are incorrect, the code should be adjusted accordingly.
Upvotes: 5