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()));
}


相关文章
|
安全 前端开发 Java
《深入理解Spring》:现代Java开发的核心框架
Spring自2003年诞生以来,已成为Java企业级开发的基石,凭借IoC、AOP、声明式编程等核心特性,极大简化了开发复杂度。本系列将深入解析Spring框架核心原理及Spring Boot、Cloud、Security等生态组件,助力开发者构建高效、可扩展的应用体系。(238字)
|
Java Unix Go
【Java】(8)Stream流、文件File相关操作,IO的含义与运用
Java 为 I/O 提供了强大的而灵活的支持,使其更广泛地应用到文件传输和网络编程中。!但本节讲述最基本的和流与 I/O 相关的功能。我们将通过一个个例子来学习这些功能。
512 1
|
Java API 数据处理
Java新特性:使用Stream API重构你的数据处理
Java新特性:使用Stream API重构你的数据处理
|
Java 大数据 API
Java Stream API:现代集合处理与函数式编程
Java Stream API:现代集合处理与函数式编程
540 100
|
Java API 数据处理
Java Stream API:现代集合处理新方式
Java Stream API:现代集合处理新方式
501 101
|
并行计算 Java 大数据
Java Stream API:现代数据处理之道
Java Stream API:现代数据处理之道
616 101
|
消息中间件 人工智能 Java
抖音微信爆款小游戏大全:免费休闲/竞技/益智/PHP+Java全筏开源开发
本文基于2025年最新行业数据,深入解析抖音/微信爆款小游戏的开发逻辑,重点讲解PHP+Java双引擎架构实战,涵盖技术选型、架构设计、性能优化与开源生态,提供完整开源工具链,助力开发者从理论到落地打造高留存、高并发的小游戏产品。
|
存储 Java 关系型数据库
Java 项目实战基于面向对象思想的汽车租赁系统开发实例 汽车租赁系统 Java 面向对象项目实战
本文介绍基于Java面向对象编程的汽车租赁系统技术方案与应用实例,涵盖系统功能需求分析、类设计、数据库设计及具体代码实现,帮助开发者掌握Java在实际项目中的应用。
515 0
|
7天前
|
Java API 开发者
Java 21 特性及示例
本文介绍了 Java 21 的新特性,包括字符串模板、顺序集合、记录模式和 switch 模式匹配,通过示例展示其用法和优势,帮助开发者提升代码简洁性与可读性,是升级至 JDK 21 的实用指南。
518 0
|
存储 数据可视化 Java
Java Stream API 的强大功能
Java Stream API 是 Java 8 引入的重要特性,它改变了集合数据的处理方式。通过声明式语法,开发者可以更简洁地进行过滤、映射、聚合等操作。Stream API 支持惰性求值和并行处理,提升了代码效率和可读性,是现代 Java 开发不可或缺的工具。
335 0
Java Stream API 的强大功能