stream根据对象的某一个属性相同的值对其另一个属性进行操作

stream根据对象的某一个属性相同的值对其另一个属性进行操作

新建一个实体类InfoPubParam,有isbn和amount两个属性

测试类

@Test
    public void Test1() {

        InfoPubParam param1 = new InfoPubParam();
        param1.setIsbn("1234");
        param1.setAmount(5L);


        InfoPubParam param2 = new InfoPubParam();
        param2.setIsbn("123434");
        param2.setAmount(2L);

        InfoPubParam param3 = new InfoPubParam();
        param3.setIsbn("156784");
        param3.setAmount(4L);


        InfoPubParam param4 = new InfoPubParam();
        param4.setIsbn("1234");
        param4.setAmount(3L);

        InfoPubParam param5 = new InfoPubParam();
        param5.setIsbn("1234");
        param5.setAmount(1L);

        List<InfoPubParam> paramList =new ArrayList<>();
        paramList .add(param1);
        paramList .add(param2);
        paramList .add(param3);
        paramList .add(param4);
        paramList .add(param5)

        List<InfoPubParam> paramList1 =new ArrayList<>();
        Map<String, InfoPubParam> infoPubParamMap = paramList.stream().collect(Collectors.toMap(InfoPubParam::getIsbn, Function.identity(), (a, b) -> {
            a.setAmount(a.getAmount() + b.getAmount());
            return a;
        }));
        for (Map.Entry<String, InfoPubParam> entry : infoPubParamMap.entrySet()) {
            paramList1.add(entry.getValue());
        }
        System.out.println(paramList1.toString());
    }

最后结果

[InfoPubParam(isbn=156784, amount=4), InfoPubParam(isbn=123434, amount=2), InfoPubParam(isbn=1234, amount=9)]

你可能感兴趣的:(Java集合,java)