Java 8 Stream:从对象列表中提取地图并汇总特定键

时间:2017-06-21 06:34:08

标签: java java-8 java-stream

我有Customer个对象的列表

class Customer {
     //Other properties
     Map<String, Object> additionalData;
}

当我收到List<Customer> customers时,我想在transactions中对一个名为additionalData的密钥求和。我怎么能用java 8流做到这一点?

1 个答案:

答案 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}}。如果这些假设不正确,则应相应地调整代码。