有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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()...

共 (2) 个答案

  1. # 1 楼答案

    你可以这样做

    Collection<Product> productsByName = tmpList.stream()
        .collect(Collectors.toMap(Product::getName, 
            Function.identity(), 
            (p1, p2) -> new Product(p1.getName(),
                p1.getCostIn() + p2.getCostIn(), p1.getCostOut() + p2.getCostOut())))
        .values();
    
  2. # 2 楼答案

    您可以在流媒体时mapcollect

    List<Product> productList = proMap.keySet().stream()
            .map(productName -> new Product(productName,
                    proMap.get(productName).stream().mapToDouble(Product::getCostIn).sum(),
                    proMap.get(productName).stream().mapToDouble(Product::getCostOut).sum()))
            .collect(Collectors.toList());
    

    另一方面,如果要查找给定产品名称的costIn/costOut,则可以直接根据特定产品名称存储它们的总和,而groupingBy,例如

    Map<String, Double> costIn = tmpList.stream()
            .collect(Collectors.groupingBy(Product::getName,
                    Collectors.summingDouble(Product::getCostIn)));