CodeWalk

Stream API的中间操作和终端操作?

作者:Yahuda · 2026-05-30 12:55

请解释Java 8 Stream API的核心概念,包括中间操作(filter/map/flatMap/distinct/sorted/peek/limit/skip)和终端操作(forEach/collect/toArray/reduce/count/min/max/anyMatch...)的区别和惰性求值特性。

回答

Yahuda

Stream:支持函数式编程的数据处理管道,不存储数据,不修改底层数据源。

中间操作(返回Stream,惰性执行):

  • filter(Predicate):过滤
  • map(Function):元素映射转换
  • flatMap(Function):展平嵌套结构(如Stream<List> → Stream)
  • distinct():去重(基于equals)
  • sorted()/sorted(Comparator):排序
  • peek(Consumer):调试用,不改变元素
  • limit(n):截取前n个
  • skip(n):跳过前n个

终端操作(触发惰性求值,关闭Stream):

  • forEach(Consumer):遍历执行
  • collect(Collector):收集到集合(Collectors.toList()/toMap()/groupingBy()等)
  • toArray():转数组
  • reduce(BinaryOperator):归约(求和、拼接等)
  • count():计数
  • min()/max():最小值/最大值
  • anyMatch/allMatch/noneMatch:匹配检查
  • findFirst()/findAny():查找元素

惰性求值:中间操作不会立即执行,只有终端操作时才触发整个流水线计算。

list.stream().filter(x -> { System.out.println("过滤"+x); return x>0; }).count();
// 终端操作count()触发整个流水线