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))
答案 0 :(得分:5)
list.stream().collect(Collectors.groupingBy(CustomerOrder::getGender,
Collectors.summingLong(CustomerOrder::getOrderAmmount));
修改强>
list.stream().collect(Collectors.groupingBy(CustomerOrder::getGender,
Collectors.summingLong(co -> co.getOrder().getAmmount()));
我没有编译它,但应该工作(有少量替换)。
答案 1 :(得分:0)
你可以使用Collectors.toMap
,它有3个参数:
以下是代码:
Map<Gender, Long> result = customerOrders.stream()
.collect(Collectors.toMap(
CustomerOrder::getGender,
co -> co.getOrder().getOrderAmount(),
Long::sum));
如果您需要指定返回地图的类型,即如果您需要按性别排序地图,则可以使用Collectors.toMap
的4参数重载:
Map<Gender, Long> result = customerOrders.stream()
.collect(Collectors.toMap(
CustomerOrder::getGender,
co -> co.getOrder().getOrderAmount(),
Long::sum,
TreeMap::new));