Java新特性Stream流开发技巧

简介: Java新特性Stream流开发技巧

1.组装多个集合的数据,避免for循环操作数据库

假如有这样一个需求,需要我们组装从数据库中查出来的Student集合以及Student对应的班级名称返回给前端StudentVO

public static List<StudentVO> assembleData(List<Long> ids) {
    List<StudentVO> result = new ArrayList<>();
    List<Student> students = this.selectBatchIds(ids);
    // 可能有小伙伴会用students的id一个个去数据库拿,但这样是不对的,会严重影响数据库性能
    for (Person p : PersonList){
        PersonVO vo = new PersonVO();
        Class c = classMapper.selectById(p.getClassId());
        p.setClassName(c.getName);
        result.add(p);
    }
    return result;
}

循环访问数据库,是会严重影响数据库性能的

优化思路就是批量获取所有数据,然后再组装数据
public static List<StudentVO> assembleData(List<Long> ids) {
    //批量查出studnt
    List<Student> students = this.selectBatchIds(ids);
    //批量查出class 也可以写条sql,在sql语句循环查(效果比你for循环里查询数据库好)
    List<Long> classIds = students.stream().map(s -> s::getClassId()).distinct().collect(Collectors.toList());
    List<Class> classes = classMapper.selectBatchIds(classIds);
    //转换成Map
    Map<String, Class> classMap =
    classes.stream().collect(Collectors.toMap(Class::getId, Function.identity()));
    //封装成StudentVO
    return s.stream().map(s -> {
        StudentVO vo = new StudentVO();
        vo.setStudent(s);
        vo.setClassName(classes.get(s.getClassId()).getName())
        return vo;
    }).collect(Collectors.toList());
}
sql参考模板
<select id="selectByUserIds" resultType="com.chenguangzhao.entities.UserInfoDTO" parameterType="java.util.List">
    SELECT
    a.id AS userId,
  a.user_name AS userName,
  b.image_url AS imageUrl
    FROM t_user a
    LEFT JOIN t_image b on a.image_id=b.id
    <where>
      <if test="userIdList.size()>0">
          a.id in
          <foreach collection="userIdList" item="id" index="index" open="(" close=")" separator=",">
            #{id}
      </foreach>
        </if>
   </where>
</select>

2.把List转换为Map

public static Map<Long, Student> listToMap(List<Student> list) {
    return list.stream().collect(Collectors.toMap(Student::getId(), Function.identity()));
}

3.按对象字段排序

public static List<Student> sortBy(List<Student> list) {
    return list.stream().sorted(
      (o1, o2) ->
        (o1.getId().compareTo(o2.getId()))
    ).collect(Collectors.toList());
}
//简化
public static List<Student> sortBy(List<Student> list) {
    return list.stream().sorted(
      Comparator.comparing(Student::getId()) //直接调用类型内部实现的CompareTo
    ).collect(Collectors.toList());
}
//倒序
public static List<Student> sortBy(List<Student> list) {
    return list.stream().sorted(
      Comparator.comparing(Student::getId()).reversed()
    ).collect(Collectors.toList());
}
//多字段排序
public static List<Student> sortBy(List<Student> list) {
    return list.stream().sorted(
      Comparator.comparing(Student::getId())
        .thenComparing(Student::getAge())
    ).collect(Collectors.toList());
}

4.求多个集合的交集

public static List<Student> intersection(List<Student> s1, List<Student> s2) {
    Map<String, Student> m1 = s1.stream().collect(Collectors.toMap(Student::getId(), Function.identity()));
    return s2.stream().filter(s -> m1.get(s.getId())).collect(Collectors.toList());
}

5.把数据分组

在开发项目中我们可能会将从数据库中查出来的数据按照字段分组(其实在数据库中分好组也可以), 但是我们有时需要在业务层面输出

在Java8之前我们可能会这样写

public static Map<String, List<Student>> toGroupingMap(List<Student> list) {
    Map<String, List<Student>> resultMap = new Map<>();
    for (Student s : list) {
        List<Student> students = resultMap.get(s.getAge());
        if (students == null) {
            List<Student> s = new ArrayList<>();
            resultMap.put(s.getAge(), s);
        }
        resultMap.put(s.getAge(), students);
    }
}

Java8之后我们仅需要用stream分组函数就行了

public static Map<String, List<Student>> toGroupingMap(List<Student> list) {
    return list.stream().collect(Collectors.grouping(Student::getAge()));
}


相关文章
|
16天前
|
人工智能 安全 IDE
一天成为Java开发高手:用飞算JavaAI实现十倍提效
“一天成为Java开发高手”曾被视为天方夜谭,但飞算JavaAI的出现改变了这一局面。这款AI开发助手通过智能引导、需求分析、自动化逻辑处理和完整代码工程生成,大幅简化了Java开发流程。它不仅帮助新手快速上手,还让资深开发者提高效率,减少调试时间。现在,参与“飞算JavaAI炫技赛”,展示你的开发实力,赢取丰厚奖品!
|
8天前
|
缓存 运维 Java
Java静态代码块深度剖析:机制、特性与最佳实践
在Java中,静态代码块(或称静态初始化块)是指类中定义的一个或多个`static { ... }`结构。其主要功能在于初始化类级别的数据,例如静态变量的初始化或执行仅需运行一次的初始化逻辑。
25 4
|
1月前
|
JavaScript 安全 Java
智慧产科一体化管理平台源码,基于Java,Vue,ElementUI技术开发,二开快捷
智慧产科一体化管理平台覆盖从备孕到产后42天的全流程管理,构建科室协同、医患沟通及智能设备互联平台。通过移动端扫码建卡、自助报道、智能采集数据等手段优化就诊流程,提升孕妇就诊体验,并实现高危孕产妇五色管理和孕妇学校三位一体化管理,全面提升妇幼健康宣教质量。
48 12
|
7天前
|
搜索推荐 Java Android开发
课时146:使用JDT开发Java程序
在 Eclipse 之中提供有 JDT环境可以实现java 程序的开发,下面就通过一些功能进行演示。 项目开发流程
|
8天前
|
存储 监控 数据可视化
SaaS云计算技术的智慧工地源码,基于Java+Spring Cloud框架开发
智慧工地源码基于微服务+Java+Spring Cloud +UniApp +MySql架构,利用传感器、监控摄像头、AI、大数据等技术,实现施工现场的实时监测、数据分析与智能决策。平台涵盖人员、车辆、视频监控、施工质量、设备、环境和能耗管理七大维度,提供可视化管理、智能化报警、移动智能办公及分布计算存储等功能,全面提升工地的安全性、效率和质量。
|
16天前
|
人工智能 Java 数据处理
Java高级应用开发:基于AI的微服务架构优化与性能调优
在现代企业级应用开发中,微服务架构虽带来灵活性和可扩展性,但也增加了系统复杂性和性能瓶颈。本文探讨如何利用AI技术,特别是像DeepSeek这样的智能工具,优化Java微服务架构。AI通过智能分析系统运行数据,自动识别并解决性能瓶颈,优化服务拆分、通信方式及资源管理,实现高效性能调优,助力开发者设计更合理的微服务架构,迎接未来智能化开发的新时代。
|
2月前
|
前端开发 Java 程序员
菜鸟之路day02-04拼图小游戏开发一一JAVA基础综合项目
本项目基于黑马程序员教程,涵盖面向对象进阶、继承、多态等知识,历时约24小时完成。项目去除了登录和注册模块,专注于单机游戏体验。使用Git进行版本管理,代码托管于Gitee。项目包含窗体搭建、事件监听、图片加载与打乱、交互逻辑实现、菜单功能及美化界面等内容。通过此项目,巩固了Java基础并提升了实际开发能力。 仓库地址:[https://gitee.com/zhang-tenglan/puzzlegame.git](https://gitee.com/zhang-tenglan/puzzlegame.git)
51 6
|
2月前
|
Java 应用服务中间件 API
【潜意识Java】javaee中的SpringBoot在Java 开发中的应用与详细分析
本文介绍了 Spring Boot 的核心概念和使用场景,并通过一个实战项目演示了如何构建一个简单的 RESTful API。
53 5
|
2月前
|
SQL Java API
|
2月前
|
前端开发 Java 数据库连接
【潜意识Java】深度解读JavaWeb开发在Java学习中的重要性
深度解读JavaWeb开发在Java学习中的重要性
42 4

热门文章

最新文章