Stream-流式操作

Stream 流式操作

Java8对集合操作功能的增强,专注于对集合的各种高效、便利、优雅的聚合操作。

获取list某个字段 组装 新list

复制代码
List<Integer> userIdList = userList.stream().map(e -> e.getUserId()).collect(Collectors.toList());

根据指定字段分组 Collectors.groupingBy()

复制代码
// 根据name字段分组,User对象值相同时不去重
Map<String, List<User>> mapByName = list.stream().collect(Collectors.groupingBy(User::getName));
// 根据name字段分组,User对象值相同时去重
Map<String, List<User>> mapByName = list.stream().collect(Collectors.groupingBy(
    e -> e.getName(),
    Collectors.mapping(e -> e, Collectors.collectingAndThen(Collectors.toSet(), ArrayList::new))));

Map<Long, List<Long>> userIdReOrderIdsMap = list.stream()
                            .collect(Collectors.groupingBy(OrderVO::getUserId,
                                    Collectors.mapping(OrderVO::getOrderId, Collectors.toList())));

去重 distinct()

复制代码
List<Integer> numList = Lists.newArrayList(1, 5, 3, 3, 6);
numList = numList.stream().distinct().collect(Collectors.toList());

// 根据指定字段去重
list = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(User::getId))), ArrayList::new));

条件过滤 filter()

复制代码
// 只要含有"小孙"的数据
list = list.stream().filter(e -> e.getName().equals("小孙")).collect(Collectors.toList());

求和

复制代码
// 基本类型
int sumAge = userList.stream().mapToInt(User::getAge).sum();
// 其他  -- 若bigDecimal对象为null,可filter()过滤掉空指针
BigDecimal totalMemberNum = userList.stream().map(User::getMemberNum).reduce(BigDecimal.ZERO, BigDecimal::add);

最大值/最小值

复制代码
Date minDate = userList.stream().map(User::getCreateTime).min(Date::compareTo).get();
Date maxDate = userList.stream().map(User::getCreateTime).max(Date::compareTo).get();
User maxUp = userList.stream().max(Comparator.comparingInt(User::getAge)).get();

差值(新增/删除)

复制代码
List<Integer> userIdListNew = Lists.newArrayList(1, 2, 3, 5, 6);
List<Integer> userIdListOld = Lists.newArrayList(1, 2, 3, 4);

// 删除人员 [4]
List<Integer> removeUserIdList = userIdListOld.stream().filter(userIdOld -> !userIdListNew.contains(userIdOld)).collect(Collectors.toList());
// 或使用hutool
List<Integer> addList = CollUtil.subtractToList(userIdListOld, userIdListNew); // [4]

// 新增人员 [5, 6]
List<Integer> addUserIdList = userIdListNew.stream().filter(userIdNew -> !userIdListOld.contains(userIdNew)).collect(Collectors.toList());
// 或使用hutool
List<Integer> addList = CollUtil.subtractToList(userIdListNew, userIdListOld); // [5, 6]

分类统计数量

复制代码
// 多字段统计 -- ex: 统计相同name下相同age的个数
Map<String, Map<Integer, Long>> map = list.stream().collect(
                Collectors.groupingBy(User::getName, Collectors.groupingBy(User::getAge, Collectors.counting()))
        );

// 单字段统计 [LongSummaryStatistics中包含总数、最小值、最大值、平均值等信息]   --  ex: 根据名称去统计
Map<String, LongSummaryStatistics> map = list.stream()
        .collect(
                Collectors.groupingBy(User::getName, Collectors.summarizingLong(User::getAge))
        );

求list重复元素值

复制代码
@Test
public void test02() throws Exception {
    List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5, 6, 1, 6, 6);
    List<Integer> repeatDataList = list.stream()
        .collect(Collectors.toMap(e -> e, e -> 1, Integer::sum))
        .entrySet().stream()
        .filter(entry -> entry.getValue() > 1)
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());
    System.out.println(repeatDataList); // [1, 6]
    
    
    // 求list对象中某一个字段的重复值
    List<String> repeatValueDataList = dictList
                    .stream().map(e -> e.getValue()).collect(Collectors.toList())
                    .stream().collect(Collectors.toMap(e -> e, e -> 1, Integer::sum))
                    .entrySet().stream()
                    .filter(entry -> entry.getValue() > 1)
                    .map(Map.Entry::getKey)
                    .collect(Collectors.toList());
}

public <T> List<T> getRepeatDataList(List<T> list) {
    return list.stream()
            // 获得元素出现频率的 Map,键为元素,值为元素出现的次数
            .collect(Collectors.toMap(e -> e, e -> 1, Integer::sum))
            // Set<Entry>转换为Stream<Entry>
            .entrySet().stream()
            // 过滤出元素出现次数大于 1 的 entry
            .filter(entry -> entry.getValue() > 1)
            // 获得 entry 的键(重复元素)对应的 Stream
            .map(Entry::getKey)
            // 转化为 List
            .collect(Collectors.toList());
}

demo

复制代码
package com.zhengqing.demo.daily.base.java8;

import cn.hutool.json.JSONUtil;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;

public class Java8_stream {
  @Test
  public void test() throws Exception {
    List<Integer> numList = Lists.newArrayList(1, 5, 3, 3, 6);
    List<User> list = Lists.newArrayList(
      User.builder().id(1).age(16).name("小张").build(),
      User.builder().id(10).age(20).name("小孙").build(),
      User.builder().id(1).age(18).name("李四").build(),
      User.builder().id(3).age(6).name("王五").build()
    );

    Map<String, List<User>> mapByName = list.stream().collect(Collectors.groupingBy(User::getName));
    System.out.println("分组:" + JSONUtil.toJsonStr(mapByName));

    numList = numList.stream().distinct().collect(Collectors.toList());
    System.out.println("去重:" + numList);

    list = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(User::getId))), ArrayList::new));
    System.out.println("根据指定字段去重:" + JSONUtil.toJsonStr(list));

    list = list.stream().filter(e -> e.getName().equals("小孙")).collect(Collectors.toList());
    System.out.println("条件过滤:" + JSONUtil.toJsonStr(list));
  }

  @Data
  @Builder
  @NoArgsConstructor
  @AllArgsConstructor
  static class User {
    private Integer id;
    private String name;
    private Integer age;
    private Date time;
  }
}
相关推荐
非优秀程序员2 小时前
第04章 邮箱大战,163 与 QQ 的暗战|《互联网产品恩仇录》
java·vue.js·架构
知已难寻3 小时前
Docker 入门:容器技术与 Docker 基础
java·运维·服务器·docker·云原生·容器
文丑颜不良啊5 小时前
LeetCode2481~2500题目解析
java·leetcode
Flynn Liang6 小时前
同一需求三套写法:用 Spring AI、LangChain4j、AgentScope Java 各实现一个带工具调用的 RAG 助手(实战对比)
java·人工智能·大模型·架构设计·spring ai·langchain4j·agentscope
聪明的笨猪猪7 小时前
实际工程问题:AI 生成 Spring Cache(@Cacheable / @CachePut / @CacheEvict)缓存注解踩坑
java·经验分享·面试·ai编程
愿有所息7 小时前
记一次 ARM64 + JDK8 上 fastjson2 的诡异数据错乱
java
秋饼7 小时前
MCP 2026-07-28 无状态协议大改版:Spring AI 2.1 多轮往返请求与网关路由落地
java·ai·技术分享·后端开发
flyingonpine8 小时前
PowerShell脚本数字签名实战:自签名证书、代码签名与信任链验证
windows·信任链
SL_staff8 小时前
JVS-BI 实战:业务人员如何用零代码 ELT + 可视化配置构建实时经营分析闭环
java·spring·全栈
SL_staff9 小时前
企业AI落地难?JVS-AI渐进式实践:安全可控、小切口验证、标准化沉淀与规模化复制
java·开源·aigc