我想准备一个简单的报告,按月显示订购产品的数量,如下所示(降序):Month Number of products2018-10 82018-11 3 我的数据: class Orders { private List<Order> orders = new ArrayList<>(); public void prepareData() { Product socks = new ProductBuilder() .setPrice(new BigDecimal("23")) .setCategory(Category.C) .setName("SOCKS") .build(); Product jacket = new ProductBuilder() .setPrice(new BigDecimal("199")) .setCategory(Category.A) .setName("JACKET") .build(); Product watch = new ProductBuilder() .setPrice(new BigDecimal("100")) .setCategory(Category.B) .setName("WATCH CASIO") .build(); Customer john = new CustomerBuilder() .setAge(18) .setName("JOHN") .setSurname("JOHNSON") .setEmail("john@johnson.com") .build(); Customer mike = new CustomerBuilder() .setAge(20) .setName("MIKE") .setSurname("MAX") .setEmail("mike@max.com") .build(); Order orderJohn = new OrderBuilder() .setQuantity(2) .setCustomer(john) .setProduct(watch) .setOrderDate(LocalDate.now()) .build(); Order orderJohn2 = new OrderBuilder() .setQuantity(4) .setCustomer(john) .setProduct(socks) .setOrderDate(LocalDate.now()) .build();
2 回答
慕妹3146593
TA贡献1820条经验 获得超9个赞
您可以将您的替换Collectors.counting()为:
Collectors.summingInt(Order::getQuantity)
(它的工作原理类似:Collectors.reducing(0, Order::getQuantity, Integer::sum))
编辑:
查看您对另一个答案的评论,这是您需要的:
Map<LocalDate, IntSummaryStatistics> ord = orders.stream().collect(Collectors.groupingBy(e -> e.getOrderDate().withDayOfMonth(1), Collectors.summarizingInt(Order::getQuantity)));
ord.entrySet().stream().sorted(Map.Entry.comparingByValue((p1,p2) -> Long.compare(p2.getSum(), p1.getSum()))).forEach(System.out::println);
添加回答
举报
0/150
提交
取消