java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java Stream流

java的Stream流处理示例小结

作者:Ramseyuu

Stream API提供了一种高效、声明式的数据处理方式,是现代 Java 编程中不可或缺的工具,合理使用可以大幅提升代码的可读性和维护性,这篇文章主要介绍了java的Stream流处理,需要的朋友可以参考下

Java Stream 流处理详解

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

一、Stream 的核心概念

1. 什么是 Stream

2. 操作类型

二、创建 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();
}

九、注意事项

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

到此这篇关于java的Stream流处理的文章就介绍到这了,更多相关java Stream流内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文