前提
class Product {
public String name;
public String category;
public String type;
public int id;
//todo:implement equals(), toString() and hashCode()
}
class Item{
public Product product;
public double cost;
}
总结方式
List items = ...;
Map stat = items.stream().collect(groupingBy(
it -> it.product,
Collectors.summarizingDouble(it -> it.cost)
));
// get some product summarizing
long count = stat.get(product).getCount();
double sum = stat.get(product).getSum();
//list all product summarizing
stat.entrySet().forEach(it ->
System.out.println(String.format("%s - count: %d, total cost: %.2f"
, it.getKey(),it.getValue().getCount(), it.getValue().getSum()));
);
合并具有相同产品的项目
首