当前位置: 首页 > news >正文

java的Stream流处理

Java Stream 流处理详解

Stream 是 Java 8 引入的一个强大的数据处理抽象,它允许你以声明式方式处理数据集合(类似于 SQL 语句),支持并行操作,提高了代码的可读性和处理效率。

一、Stream 的核心概念

1. 什么是 Stream

  • 不是数据结构:不存储数据,只是从数据源(集合、数组等)获取数据

  • 函数式风格:支持 lambda 表达式和方法引用

  • 延迟执行:许多操作(中间操作)不会立即执行,只有遇到终止操作才会执行

  • 可消费性:Stream 只能被消费一次,用完即失效

2. 操作类型

  • 中间操作(Intermediate Operations):返回 Stream 本身,可以链式调用(如 filter, map)

  • 终止操作(Terminal Operations):产生最终结果或副作用(如 forEach, collect)

二、创建 Stream 的多种方式

// 1. 从集合创建
List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream1 = list.stream();       // 顺序流
Stream<String> parallelStream = list.parallelStream(); // 并行流// 2. 从数组创建
String[] array = {"a", "b", "c"};
Stream<String> stream2 = Arrays.stream(array);// 3. 使用Stream.of()
Stream<String> stream3 = Stream.of("a", "b", "c");// 4. 使用Stream.generate() 无限流
Stream<Double> randomStream = Stream.generate(Math::random).limit(5);// 5. 使用Stream.iterate() 迭代流
Stream<Integer> iterateStream = Stream.iterate(0, n -> n + 2).limit(10);

三、常用的中间操作

1. 过滤操作

// filter(Predicate) 过滤符合条件的元素
List<String> filtered = list.stream().filter(s -> s.startsWith("a")).collect(Collectors.toList());

2. 映射操作

// map(Function) 将元素转换为其他形式
List<Integer> lengths = list.stream().map(String::length).collect(Collectors.toList());// flatMap 将多个流合并为一个流
List<String> flatMapped = list.stream().flatMap(s -> Stream.of(s.split(""))).collect(Collectors.toList());

3. 去重和排序

// distinct() 去重
List<String> distinct = list.stream().distinct().collect(Collectors.toList());// sorted() 自然排序
List<String> sorted = list.stream().sorted().collect(Collectors.toList());// sorted(Comparator) 自定义排序
List<String> customSorted = list.stream().sorted((s1, s2) -> s2.compareTo(s1)).collect(Collectors.toList());

4. 其他中间操作

// limit(long) 限制元素数量
// skip(long) 跳过前N个元素
// peek(Consumer) 查看流中元素(主要用于调试)

四、常用的终止操作

1. 遍历操作

// forEach(Consumer) 遍历每个元素
list.stream().forEach(System.out::println);

2. 收集结果

// collect(Collector) 将流转换为集合或其他形式
List<String> collectedList = stream.collect(Collectors.toList());
Set<String> collectedSet = stream.collect(Collectors.toSet());
Map<String, Integer> map = stream.collect(Collectors.toMap(Function.identity(), String::length));

3. 聚合操作

// count() 计数
long count = list.stream().count();// max/min(Comparator) 最大/最小值
Optional<String> max = list.stream().max(Comparator.naturalOrder());// reduce 归约操作
Optional<Integer> sum = Stream.of(1, 2, 3).reduce(Integer::sum);

4. 匹配操作

// anyMatch 任意元素匹配
boolean anyStartsWithA = list.stream().anyMatch(s -> s.startsWith("a"));// allMatch 所有元素匹配
boolean allStartsWithA = list.stream().allMatch(s -> s.startsWith("a"));// noneMatch 没有元素匹配
boolean noneStartsWithZ = list.stream().noneMatch(s -> s.startsWith("z"));

五、数值流特化

Java 8 提供了专门的数值流,避免装箱拆箱开销:

// IntStream, LongStream, DoubleStream
IntStream intStream = IntStream.range(1, 100); // 1-99
DoubleStream doubleStream = DoubleStream.of(1.1, 2.2);// 常用数值操作
int sum = IntStream.rangeClosed(1, 100).sum(); // 1-100的和
OptionalDouble avg = IntStream.of(1, 2, 3).average();

六、并行流处理

// 创建并行流
List<String> parallelProcessed = list.parallelStream().filter(s -> s.length() > 1).collect(Collectors.toList());// 注意事项:
// 1. 确保操作是线程安全的
// 2. 避免有状态的操作
// 3. 数据量足够大时才使用并行流

七、收集器(Collectors)的高级用法

// 分组
Map<Integer, List<String>> groupByLength = list.stream().collect(Collectors.groupingBy(String::length));// 分区
Map<Boolean, List<String>> partition = list.stream().collect(Collectors.partitioningBy(s -> s.startsWith("a")));// 连接字符串
String joined = list.stream().collect(Collectors.joining(", "));// 汇总统计
IntSummaryStatistics stats = list.stream().collect(Collectors.summarizingInt(String::length));

八、实际应用示例

示例1:处理对象集合

List<Person> people = ...;// 获取所有成年人的姓名列表
List<String> adultNames = people.stream().filter(p -> p.getAge() >= 18).map(Person::getName).collect(Collectors.toList());// 按城市分组
Map<String, List<Person>> byCity = people.stream().collect(Collectors.groupingBy(Person::getCity));// 计算每个城市的平均年龄
Map<String, Double> avgAgeByCity = people.stream().collect(Collectors.groupingBy(Person::getCity,Collectors.averagingInt(Person::getAge)));

示例2:文件处理

// 读取文件并处理
try (Stream<String> lines = Files.lines(Paths.get("data.txt"))) {long wordCount = lines.flatMap(line -> Arrays.stream(line.split("\\s+"))).filter(word -> word.length() > 0).count();
} catch (IOException e) {e.printStackTrace();
}

九、注意事项

  1. 流只能消费一次:尝试第二次使用已关闭的流会抛出 IllegalStateException

  2. 避免修改源数据:流操作期间不应修改源集合

  3. 合理使用并行流:并非所有情况都适合并行,小数据量可能适得其反

  4. 注意自动装箱:数值操作尽量使用原始类型特化流(IntStream等)

  5. 延迟执行特性:没有终止操作,中间操作不会执行

Stream API 提供了一种高效、声明式的数据处理方式,是现代 Java 编程中不可或缺的工具。合理使用可以大幅提升代码的可读性和维护性。

相关文章:

  • MySql(进阶)
  • macOS 15 (Sequoia) 解除Gatekeeper限制
  • wget、curl 命令使用场景与命令实践
  • 第八讲 | stack和queue的使用及其模拟实现
  • MySQL 数据库故障排查指南
  • 浏览器的B/S架构和C/S架构
  • 什么是卷积神经网络
  • QtGUI模块功能详细说明,事件与输入处理(五)
  • 无人机飞控算法开发实战:从零到一构建企业级飞控系统
  • JDS-算法开发工程师-第9批
  • Linux | Uboot-Logo 修改文档(第十七天)
  • HTML5中的Microdata与历史记录管理详解
  • linux内核pinctrl/gpio子系统驱动笔记
  • 第6讲、全面拆解Encoder、Decoder内部模块
  • stm32 WDG看门狗
  • 【人工智能】全面掌控:使用Python进行深度学习模型监控与调优
  • 深入浅出:Spring Boot 中 RestTemplate 的完整使用指南
  • 虚拟内存笔记(三)虚拟内存替换策略与机制
  • 小智AI机器人 - 代码框架梳理2
  • 论文解读:MP-SfM: Monocular Surface Priors for Robust Structure-from-Motion
  • 韩国总统选战打响:7人角逐李在明领跑,执政党临阵换将陷入分裂
  • 行知读书会|换一个角度看见社会
  • 巴基斯坦称对印度发起军事行动
  • “仓促、有限”,美英公布贸易协议框架,两国分别获得了什么?
  • 九家企业与上海静安集中签约,投资额超10亿元
  • 陕西澄城樱桃在上海推介,向长三角消费者发出“甜蜜之邀”