Java中Stream流介绍

Java 8引入的Stream API是Java中处理集合的一种高效方式,它提供了一种高级的迭代方式,允许你以声明式方式处理数据。Stream API可以对数据执行复杂的查询操作,而不需要编写冗长且复杂的循环语句。下面是一些使用Stream API的常见场景和示例:

1. 过滤(Filtering)

过滤出满足特定条件的元素。

java 复制代码
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Diana");
List<String> filteredNames = names.stream()
    .filter(name -> name.startsWith("A"))
    .collect(Collectors.toList());
// 结果: ["Alice"]

2. 映射(Mapping)

将元素转换为其他形式或提取信息。

java 复制代码
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Diana");
List<Integer> nameLengths = names.stream()
    .map(String::length)
    .collect(Collectors.toList());
// 结果: [5, 3, 7, 5]

3. 排序(Sorting)

对流中的元素进行排序。

java 复制代码
List<String> names = Arrays.asList("Charlie", "Bob", "Alice", "Diana");
List<String> sortedNames = names.stream()
    .sorted()
    .collect(Collectors.toList());
// 结果: ["Alice", "Bob", "Charlie", "Diana"]

4. 聚合(Aggregating)

对元素进行聚合操作,例如求和、找到最大或最小元素等。

java 复制代码
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
    .reduce(0, Integer::sum);
// 结果: 15

5. 收集(Collecting)

将流转换为其他形式,如列表、集合或映射。

java 复制代码
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Diana");
Set<String> nameSet = names.stream()
    .collect(Collectors.toSet());
// 结果: ["Alice", "Bob", "Charlie", "Diana"] 的集合

6. 并行操作(Parallel Operations)

利用多核处理器的能力自动并行化执行操作。

java 复制代码
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Diana");
List<String> upperCaseNames = names.parallelStream()
    .map(String::toUpperCase)
    .collect(Collectors.toList());
// 结果: ["ALICE", "BOB", "CHARLIE", "DIANA"]

7. 去重(Distinct)

移除流中重复的元素。

java 复制代码
List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 5);
List<Integer> distinctNumbers = numbers.stream()
    .distinct()
    .collect(Collectors.toList());
// 结果: [1, 2, 3, 4, 5]

Stream API通过这些操作提供了处理集合数据的强大工具,使得代码既简洁又易读。特别是在处理大量数据时,利用Stream的并行能力可以显著提高程序的性能。

相关推荐
Sylvia-girl3 小时前
Java——抽象类
java·开发语言
Yana.nice5 小时前
Bash函数详解
开发语言·chrome·bash
Touper.6 小时前
Redis 基础详细介绍(Redis简单介绍,命令行客户端,Redis 命令,Java客户端)
java·数据库·redis
m0_535064606 小时前
C++模版编程:类模版与继承
java·jvm·c++
虾条_花吹雪7 小时前
Using Spring for Apache Pulsar:Message Production
java·ai·中间件
tomorrow.hello7 小时前
Java并发测试工具
java·开发语言·测试工具
Moso_Rx7 小时前
javaEE——synchronized关键字
java·java-ee
晓13137 小时前
JavaScript加强篇——第四章 日期对象与DOM节点(基础)
开发语言·前端·javascript
老胖闲聊7 小时前
Python I/O 库【输入输出】全面详解
开发语言·python
张小洛8 小时前
Spring AOP 是如何生效的(入口源码级解析)?
java·后端·spring