工作中常用的java开发stream流处理

本文总结了工作中常用的几类stream流处理方法。

stream流处理List

Java Stream流式处理
Stream流
1.stream().map单独处理List中每个元素

示例:
List<HjyCommunityDto> dtoList = hjyCommunityMapper.queryList(community);

List<HjyCommunityVo> voList = dtoList.stream().map(dto -> {
   //对象拷贝
   HjyCommunityVo communityVo = OrikaUtils.convert(dto, HjyCommunityVo.class);
   return communityVo;
}).collect(Collectors.toList());

2.还可以结合filter实现数据过滤等操作,filter中传的时布尔判断

Objects.nonNull()
Objects.isNull()
// 查找过滤出符合指定条件的数据
xxxList.stream().filter(map -> map.get("id").toString().equals(aaa.getId().toString())).collect(Collectors.toList());

3.收集指定字段的值

List<Long> userIdList1 = userList.stream()
        //.map(user -> user.getUserId())
        .map(User::getUserId)
        .collect(Collectors.toList());

4.自定义处理,加入流遍历元素时进行逻辑判断

/做一些自定义处理,收集返回的元素
userList.stream()
        .map(user -> {
            String tel = user.getTel();
            if (StringUtils.isNotBlank(tel) && tel.length() == 11) {
                //手机号脱敏
                tel = tel.replace(tel.substring(3, 7), "****");
                //属性改变
                user.setTel(tel);
            }
            //如果返回的就是原对象(引用相同),则后续需要collect()才会将元素的属性变化应用到流中对应的元素上,否则修改会被丢弃(无效)
            //此时流中的元素已经是目标对象了,无需把collect()返回的新集合赋给userList
            return user;
        })
        .collect(Collectors.toList());
        List<xxx> allList = new ArrayList<>();
        xxList.stream().forEach(t ->{
            AllInfo allInfo = new AllInfo();
            BeanUtils.copyProperties(t,allInfo);
            allList.add(allInfo);
        });

List转Map

1…以List中类的某个字段-通常是id来作为map的key,原List作为value

Map<String, List<AbcDetail>> testMap =  details.stream().collect(Collectors.groupingBy(AbcDetail::getType));

2.id为key,name为value

Map<String, String> stringListMap = globalconstList.stream().collect(Collectors.toMap(Globalconst::getInteriOrid, Globalconst::getConstDisplayName));

3.list转单字段list

 List<String> userIds = selective1.stream().map(ResourcesWorkloadCalculate::getModuleId).collect(Collectors.toList());

参考

Map遍历

Map<String,String> map = new HashMap<String,String>();
for (String key:map.keySet()){
     System.out.println("key=  "+key+"   and value=  "+map.get(key));
}

对象属性拷贝

对象属性拷贝-实现字段名的两个对象之间的字段数据复制
1.工具类Orika
2.使用Json进行字段转换
3.当字段不多时,通过set方法设值

对象属性拷贝-根据两个对象字段名进行数据复制

import org.springframework.beans.BeanUtils;
BeanUtils.copyProperties(源对象,目标对象);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值