lambda我想在这个块中转换成java 8流?
在这个模块中如何转换为Java 8流语法
List<Product> tmpList = new ArrayList<>();
tmpList.add(new Product("prod1", "cat2", "t1", 100.23, 50.23));
tmpList.add(new Product("prod2", "cat1", "t2", 50.23, 50.23));
tmpList.add(new Product("prod1", "cat1", "t3", 200.23, 100.23));
tmpList.add(new Product("prod3", "cat2", "t1", 150.23, 50.23));
tmpList.add(new Product("prod1", "cat2", "t1", 100.23, 10.23));
Map<String, List<Product>> proMap = tmpList.stream().collect(Collectors.groupingBy(Product::getName));
//start
List<Product> productList = new ArrayList<>(); //
for(String productName : proMap.keySet()) {
double totalCostIn = proMap.get(productName).stream().mapToDouble(Product::getCostIn).sum();
double totalCostOut = proMap.get(productName).stream().mapToDouble(Product::getCostOut).sum();
productList.add(new Product(productName,totalCostIn,totalCostOut));
}
// how to convert to java 8 stream grammer in this block ?
List<Product> productList = proMap.entrySet().stream()...
# 1 楼答案
你可以这样做
# 2 楼答案
您可以在流媒体时
map
和collect
另一方面,如果要查找给定产品名称的costIn/costOut,则可以直接根据特定产品名称存储它们的总和,而
groupingBy
,例如