Search code examples
javalistjava-stream

Sum of attribute value in Object List


I have an order which contains a list of order items List<OrderItem>. As for the order item.

public class OrderItem {
  private long itemId;
  private String itemName;
  private String ownerName;
  private double value;

  // all the related constructors, mutators and accessors are included.
}

If in this list I have the following items

OrderItem(1,"item1","John",12.00);
OrderItem(2,"item2","John",385.00);
OrderItem(3,"item3","John",20.00);
OrderItem(4,"item4","Doe",19.00);

And I want to calculate the sum of value from which the order owner's name is the same.

e.g. if owner name is "John",then return 417.00, if name is "Doe", then it is 19.00.

How can I do this through Java stream? Many thanks


Solution

  • Assuming you have a list of OrderItems, we can group them by ownerName and do a sum as a downstream collector:

    List<OrderItem> items = List.of(
                  new OrderItem(1,"item1","John",12.00);
                  new OrderItem(2,"item2","John",385.00);
                  new OrderItem(3,"item3","John",20.00);
                  new OrderItem(4,"item4","Doe",19.00));
    
    Map<String, Double> result = items.stream()
            .collect(Collectors.groupingBy(OrderItem::ownerName,
                     Collectors.summingDouble(OrderItem::value)));
    

    From the result map we can get each value by the owner name:

    System.out.println(result.get("John")); //prints 417.00