gpt4 book ai didi

java - 将 List 分组到 Map

转载 作者:搜寻专家 更新时间:2023-11-01 02:20:52 24 4
gpt4 key购买 nike

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

}

我想实现 java 流等效于:

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

谢谢!

编辑:我过度简化了问题 - CustomerOrder 包含一个订单,其中包含 orderAmount

我已经设法到达 Map<Gender, List<Long>>通过类似的东西:

Map<Gender, List<Long>> map = orders.stream()
.collect(Collectors.groupingBy(CustomerOrder::getGender))

最佳答案

list.stream().collect(Collectors.groupingBy(CustomerOrder::getGender,
Collectors.summingLong(CustomerOrder::getOrderAmmount));

编辑

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

我没有编译这个,但应该可以工作(有小的替换)。

关于java - 将 List<CustomerOrder> 分组到 Map<Gender, Money>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43999038/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com