如果您只想打印到控制台,则可以按如下方式完成:
invoiceList.forEach(i -> System.out.println(i.getName() + " " + (i.getPrice() * i.getQty())));
如果没有,请继续阅读:
Using the toMap collector
Map<String, Double> result =
invoiceList.stream()
.collect(Collectors.toMap(Invoice::getName,
e -> e.getPrice() * e.getQuantity()));
这基本上创建了一个映射,其中键是 Invoice 名称,值是给定 Invoice 的发票价格和数量的乘积。
Using the groupingBy collector
但是,如果可以有多个同名发票,那么您可以使用groupingBy 收集器和summingDouble 作为下游收集器:
Map<String, Double> result =
invoiceList.stream()
.collect(groupingBy(Invoice::getName,
Collectors.summingDouble(e -> e.getPrice() * e.getQuantity())));
这会将Invoice 按名称分组,然后对每个组求和e.getPrice() * e.getQuantity() 的结果。
更新:
如果您想要toMap 版本并且过滤结果然后按值升序排序,可以按如下方式完成:
Map<String, Double> result = invoiceList.stream()
.filter(e -> e.getPrice() * e.getQuantity() > 100)
.sorted(Comparator.comparingDouble(e -> e.getPrice() * e.getQuantity()))
.collect(Collectors.toMap(Invoice::getName,
e -> e.getPrice() * e.getQuantity(),
(left, right) -> left,
LinkedHashMap::new));
或使用groupingBy 方法:
Map<String, Double> result =
invoiceList.stream()
.collect(groupingBy(Invoice::getName,
Collectors.summingDouble(e -> e.getPrice() * e.getQuantity())))
.entrySet()
.stream()
.filter(e -> e.getValue() > 100)
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue, (left, right) -> left,
LinkedHashMap::new));