Java使用Stream流

在实际的开发工作中,集合是我们非常常用的一种。
当我们想对集合内的对象加工时,你是不是首先想到了for循环?

其实在java8以后,引入的Stream流,同时搭配lambda的使用,可以支持一系列复杂的操作,使我们操作集合时更加方便的同时,也会使代码看起来更加简洁

假设我们有一个集合

List<Model> modelList=xxMapper.selectModelInfo();

我们可以借助Stream对modelList进行一系列操作

1.循环

modelList.Stream.map(model->{
	model.setName("mm");
	return model;
}).collect(Collectors.toList());

2.提取某个元素成新的集合

List<String> nameList=modelList.stream().map(
Model::getName).distinct().collect(Collectors.toList()
);


taCodeList=settlestList.stream().map(x-> x.getTano() ).collect(Collectors.toList());

 2.1.提取某几个元素成新的集合

  List<DisCodeAndCustomerIdRespBo> respBoList=tpAcctSeqList.stream().map(
                tpAcctSeq -> new DisCodeAndCustomerIdRespBo(tpAcctSeq.getDisCode(),tpAcctSeq.getCustomerId())
                ).collect(Collectors.toList());

3.转成map

Map<String,Model> modelMap = modelList.stream().collect(
Collectors.toMap(Model::getName,model -> model,(s, s2) -> s2)
);

4.转成map并分组

Map<String, List<Model>> modelMap = modelList.stream().collect(
Collectors.groupingBy( Model::getName)
);

5.过滤

modelList=modelList.stream().filter(
item -> "xiaoMing".equals(item.getName())
).collect(Collectors.toList());

 5.1.过滤取符合条件的第一个

  Bean bean=beanList.stream().filter(x->
                x.getId().equals(id)).findFirst().get();

6.先按某个字段分组,再对某个字段汇总

        
        Map<String, List<RptCustFee>> channelFeeMap = rptCustFeeList.stream().collect(
                Collectors.groupingBy(RptCustFee::getChannelId));
        Map<String,BigDecimal> channelBalanceAmtMap=new HashMap<>();
        
        channelFeeMap.forEach((k,v)->{
            channelBalanceAmtMap.put(k,
                    v.stream().map(RptCustFee::getBalanceAmt).reduce(BigDecimal.ZERO,BigDecimal::add));
        });

后续会持续完善~~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值