Java 流(Stream)API

一、理论说明

1. 流的定义

Java 流(Stream)是 Java 8 引入的新特性,用于对集合(如 List、Set)或数组进行高效的聚合操作(如过滤、映射、排序)和并行处理。流不存储数据,而是按需计算,支持链式调用,使代码更简洁、易读。

2. 流与集合的区别

特性集合(Collection)流(Stream)
数据存储存储元素,占用内存不存储数据,按需计算
遍历方式外部迭代(手动 for/foreach)内部迭代(自动处理)
一次性使用可重复遍历只能消费一次(类似迭代器)
延迟执行立即执行中间操作延迟,终止操作触发执行
并行支持需要手动实现多线程直接支持并行流(parallelStream()

二、流的创建与操作

1. 创建流

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class StreamExample {
    public static void main(String[] args) {
        // 1. 从集合创建
        List<String> list = Arrays.asList("a", "b", "c");
        Stream<String> stream = list.stream();

        // 2. 从数组创建
        String[] array = {"a", "b", "c"};
        Stream<String> arrayStream = Arrays.stream(array);

        // 3. 使用 Stream.of()
        Stream<String> ofStream = Stream.of("a", "b", "c");

        // 4. 创建无限流
        Stream<Integer> infiniteStream = Stream.iterate(0, n -> n + 2);
        infiniteStream.limit(5).forEach(System.out::println); // 输出: 0, 2, 4, 6, 8
    }
}

2. 中间操作(返回新的流)

使用时需注意:流只能消费一次,消费后需重新创建。并行流适用于计算密集型任务,避免 I/O 操作。合理选择中间操作和终止操作,避免过度使用复杂流。流 API 是 Java 8 最具影响力的特性之一,广泛应用于数据处理、微服务、ORM 框架等场景。

  • 过滤filter(Predicate<T>)
  • 映射map(Function<T, R>)
  • 排序sorted() 或 sorted(Comparator<T>)
  • 去重distinct()
  • 截断limit(long maxSize)
  • 跳过skip(long n)
    List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 5);
    List<Integer> evenNumbers = numbers.stream()
            .filter(n -> n % 2 == 0)    // 过滤偶数
            .distinct()                // 去重
            .sorted()                  // 排序
            .collect(Collectors.toList()); // [2, 4]

    3. 终止操作(触发计算并关闭流)

  • 聚合count()max()min()
  • 匹配anyMatch()allMatch()noneMatch()
  • 收集collect(Collectors.toList())toSet()toMap()
  • 归约reduce()
  • 遍历forEach()
    List<String> words = Arrays.asList("apple", "banana", "cherry");
    
    // 计算总长度
    int totalLength = words.stream()
            .mapToInt(String::length)
            .sum(); // 结果: 5 + 6 + 6 = 17
    
    // 检查是否所有单词长度大于 3
    boolean allLong = words.stream()
            .allMatch(w -> w.length() > 3); // true

    三、并行流(Parallel Stream)

    通过parallelStream()stream().parallel()创建并行流,利用多线程加速处理(适用于大数据量)。

    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
    int sum = numbers.parallelStream()
            .mapToInt(Integer::intValue)
            .sum();

    注意:并行流的线程安全问题,避免在流操作中修改共享状态。

    四、Collectors 工具类

    Collectors提供了丰富的收集器,用于将流结果转换为集合、Map 或进行分组统计。

    1. 集合收集

    List<String> names = people.stream()
            .map(Person::getName)
            .collect(Collectors.toList());

    2. 分组统计

    Map<Integer, List<Person>> ageGroups = people.stream()
            .collect(Collectors.groupingBy(Person::getAge));

    3. 字符串连接

    String joined = people.stream()
            .map(Person::getName)
            .collect(Collectors.joining(", ", "[", "]"));
    // 结果: "[Alice, Bob, Charlie]"

    五、应用实例

    1. 筛选与映射

    class Product {
        private String name;
        private double price;
        private Category category;
    
        // 构造方法、getter/setter 略
    }
    
    enum Category { FOOD, ELECTRONICS, CLOTHING }
    
    // 统计电子产品的平均价格
    List<Product> products = getProductList();
    double avgPrice = products.stream()
            .filter(p -> p.getCategory() == Category.ELECTRONICS)
            .mapToDouble(Product::getPrice)
            .average()
            .orElse(0.0);

    2. 分页处理

    List<Product> page2 = products.stream()
            .skip(10)  // 跳过前10条
            .limit(10) // 取10条
            .collect(Collectors.toList());

    六、自我总结

  • Java 流 API 提供了一种高效、优雅的方式处理集合数据,其核心优势包括:

  • 代码简洁:链式调用减少冗余代码。
  • 内部迭代:自动处理遍历逻辑,提升可读性。
  • 并行支持:简化多线程编程,提升大数据处理性能。
  • 延迟执行:避免不必要的计算,优化性能。

      七、面试题

    题目:

    答案;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值