简体   繁体   English

我想在此块中转换为Java 8流吗?

[英]i want to convert to java 8 stream in this block?

how to convert to Java 8 stream grammar in this block? 如何在此块中转换为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()...

You may do it like so, 你可以这样做

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

You can map and collect while streaming 您可以在流式传输时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());

on the other hand, if you were to lookup costIn/costOut given a product name you could have directly stored the sum of these against a particular product name while groupingBy , eg 在另一方面,如果你要查找海东青/ costOut给定的产品名称,你可能已经直接存储这些的总和与特定的产品名称,而groupingBy ,如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM