stream 流的简单使用(二)


前言

需求:我需要给List中对象的属性phone进行赋值,然后回传给前端。当前的属性phone的值在另一张表中。


提示:以下是本篇文章正文内容,下面案例可供参考

一、使用步骤

1.示例代码

        List<MecReceiveLine> mecReceiveLines = mapper.selectByDepartId(departId);
        //转换为 VO
        List<MecReceiveLineVO> mecReceiveLineVOS = BeanHelper.copyWithCollection(mecReceiveLines, MecReceiveLineVO.class);

        List<String> departIds = mecReceiveLines.stream().map(mecReceiveLine -> mecReceiveLine.getDepartId())
                .collect(Collectors.toList());
        List<MecDepartInfo> mecDepartInfoList = mecDepartInfoBiz.selectByIds(departIds);
        // 收集到List,

        // 将List对象转换为map;(Function.identity())再用对象作为value。
        /**
        * 以对象的主键id,作用key,确保准确对应。
    */
        Map<String, MecDepartInfo> collect = mecDepartInfoList.stream().collect(Collectors.toMap(MecDepartInfo::getCustPk, Function.identity()));
        // 目标:循环VOS对象,对其phone属性进行赋值。处理一定是目标对象,进行了赋值,也是需求所在。
        for (MecReceiveLineVO mecReceiveLineVO : mecReceiveLineVOS) {
            MecDepartInfo mecDepartInfo = collect.get(mecReceiveLineVO.getDepartId());
            if (mecDepartInfo != null){
                mecReceiveLineVO.setPhoneNumber(mecDepartInfo.getCustMobile());
            }
        }

2.接口配置文件(SQL)

<!--批量查询-->
<select id="selectByDepartIds" resultType="com.guanke.dmp.mec.entity.MecDepartInfo">
    select
    *
    from mec_depart_info
    where ( 1 = 1 )
    <if test="departIds != null and departIds.size != 0">
        and cust_pk in
        <foreach collection="departIds" item="item" open=" ( " close=" ) " separator=",">
            #{item}
        </foreach>
    </if>
</select>

此处使用了子查询动态sql

3.Bean工具类

/**
 * @author Yingyu Wei
 * @date 2020-03-18
 */
@Slf4j
public class BeanHelper {
    
    public static <T> T copyProperties(Object source, Class<T> target){
        try {
            T t = target.newInstance();
            BeanUtils.copyProperties(source, t);
            return t;
        } catch (Exception e) {
            log.error("【数据转换】数据转换出错,目标对象{}构造函数异常", target.getName(), e);
            throw new RuntimeException("【数据转换】数据转换出错");
        }
    }

    public static <T> List<T> copyWithCollection(List<?> sourceList, Class<T> target){
        try {
            return sourceList.stream().map(s -> copyProperties(s, target)).collect(Collectors.toList());
        } catch (Exception e) {
            log.error("【数据转换】数据转换出错,目标对象{}构造函数异常", target.getName(), e);
                        throw new RuntimeException("【数据转换】数据转换出错");
        }

    }

    public static <T> Set<T> copyWithCollection(Set<?> sourceList, Class<T> target){
        try {
            return sourceList.stream().map(s -> copyProperties(s, target)).collect(Collectors.toSet());
        } catch (Exception e) {
            log.error("【数据转换】数据转换出错,目标对象{}构造函数异常", target.getName(), e);
                        throw new RuntimeException("【数据转换】数据转换出错");
        }
    }
}

补充

示例2

需求:需要对List中的对象的属性赋值进行赋值。
使用:forEach() 方法,不是使用流了。

//  skuList.stream().map(sku1 -> sku1.setSpuId(spuDTO.getId())); 错误
skuList.forEach(sku1 -> sku1.setSpuId(spuDTO.getId()));

总结

笔记总结:
1,给List中的属性赋值时,需要遍历,就用stream 流经行操作。
1.1,示例代码1 需求中对象的属性是变化的;示例代码2 需求中对象的属性值是固定的,所以用forEach()比较快。
2,list转换为map时,也可以采用流,并用list对象中的id(一般都是用id,因为它不会重复,符合key的要求。)作为key,用对象作为Value。

// @AllArgsConstructor
推荐文章:link.s

2021年3月25日
补充:对象属性的值不变,可以用forEach()。(ps:这不是流操作)


版权声明:本文为weixin_47742051原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。