我有Customer
个对象的列表
class Customer {
//Other properties
Map<String, Object> additionalData;
}
当我收到List<Customer> customers
时,我想在transactions
中对一个名为additionalData
的密钥求和。我怎么能用java 8流做到这一点?
答案 0 :(得分:5)
您可以将列表中的每个元素映射到相应映射中“transactions”键的值,然后将这些值相加:
int sum = customers.stream()
.map(c->(Integer)c.additionalData.get("transactions"))
.filter(Objects::nonNull)
.mapToInt (Integer::intValue)
.sum();
例如:
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);
输出:
sum is 21
此代码假设additionalData
成员永远不会null
,而"transactions"
密钥的值(如果它存在于Map
中)始终为{{ 1}}。如果这些假设不正确,则应相应地调整代码。