gpt4 book ai didi

java - 我想在这个 block 中转换为java 8流?

转载 作者:行者123 更新时间:2023-12-01 17:46:49 26 4
gpt4 key购买 nike

如何在该 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()...

最佳答案

你可以这样做,

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

关于java - 我想在这个 block 中转换为java 8流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54274386/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com