stream 合并list


public class Test02 {
    public static void main(String[] args) {

        System.out.println(JSON.toJSONString(getSumPriceList()));

    }

    private  static Map<String, Product> getSumPriceList () {

        List<Product> list = new ArrayList<>();

        Product p1 = new Product("iphone", 9000);
        Product p2 = new Product("iphone", 8000);

        Product p3 = new Product("oppo", 6000);
        Product p4 = new Product("oppo", 7000);

        list.add(p1);
        list.add(p2);
        list.add(p3);
        list.add(p4);

        return list.stream().collect(Collectors.toMap(Product::getName, Function.identity(), (t1, t2) -> {
            t1.setPrice(t1.getPrice() + t2.getPrice());
            return t1;
        }));
    }
}

console

{"oppo":{"name":"oppo","price":13000},"iphone":{"name":"iphone","price":17000}}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM