Java 8 Stream: Extracting a map from a list of objects and a specific key

I have a list of objects Customer

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

When I received List<Customer> customers, I want to sum the key with the name transactionsin additionalData. How can I do this using java 8 threads?

+4
source share
1 answer

You can match each item in your list with a "transaction" key on the corresponding map and then summarize these values:

int sum = customers.stream()
                   .map(c->(Integer)c.additionalData.get("transactions"))
                   .filter(Objects::nonNull)
                   .mapToInt (Integer::intValue)
                   .sum();

For instance:

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);

Conclusion:

sum is 21

This code assumes that the member is additionalDatanever null, and the key value "transactions"(if it exists in Map) is always equal Integer. If these assumptions are incorrect, the code should be adjusted accordingly.

+5

Source: https://habr.com/ru/post/1679770/


All Articles