List of <CustomerOrder> groupings in Map <Gender, Money>

public class CustomerOrder {

    private final Gender gender;
    private final Order order;

    public Gender getGender() {
        return gender;
    }

    public Order getOrder() {
        return order;
    }

}

public class Order {

    private final long orderAmount;

    public long getOrderAmount() {
        return orderAmount;
    }

}

I would like to get the equivalent of java streaming:

SELECT Gender, SUM(orderAmount) FROM orders
GROUP BY Gender;

Thank!

EDIT: I simplified the problem - CustomerOrder contains an order that contains orderAmount

I managed to get to Map<Gender, List<Long>>something like:

Map<Gender, List<Long>> map = orders.stream()
    .collect(Collectors.groupingBy(CustomerOrder::getGender))
+4
source share
2 answers
list.stream().collect(Collectors.groupingBy(CustomerOrder::getGender,
            Collectors.summingLong(CustomerOrder::getOrderAmmount));

EDIT

list.stream().collect(Collectors.groupingBy(CustomerOrder::getGender,
            Collectors.summingLong(co -> co.getOrder().getAmmount()));

I did not compile this, but should work (with minor replacements).

+5
source

You can use Collectors.toMapone that has 3 arguments:

  • Display function for creating keys
  • Display function for creating values
  • A merge function that is used to resolve conflicts between values ​​associated with the same key.

:

Map<Gender, Long> result = customerOrders.stream()
    .collect(Collectors.toMap(
        CustomerOrder::getGender,
        co -> co.getOrder().getOrderAmount(),
        Long::sum));

, .. , , 4 Collectors.toMap:

Map<Gender, Long> result = customerOrders.stream()
    .collect(Collectors.toMap(
        CustomerOrder::getGender,
        co -> co.getOrder().getOrderAmount(),
        Long::sum,
        TreeMap::new));
0

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


All Articles