Stream 详解,看完就会版。

Stream 是 Java 8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作。

先理解,然后动手,工具方法在后面。

当你使用 Stream 时,你会通过 3 个阶段来建立一个操作流水线。

#

阶段

说明

1

生成

创建一个 Stream 。

2

操作

在一个或多个步骤中,指定将初始 Stream 转换为另一个 Stream 的中间操作。

3

数据收集

使用一个终止操作来产生一个结果。该操作会强制它之前的延迟操作立即执行。在这之后,该 Stream 就不会再被使用了。

例如:

String[] array = new String[]{"hello", "world", "goodbye"};
List<String> list = Arrays
    .stream(array)                  // 1. 生成
    .map(String::toUpperCase)       // 2. 操作
    .collect(Collectors.toList());  // 3. 数据收集
  1. 生成:创建 Stream

有多种方式可以获得 Stream 对象:

  • 如果你向通过数组( 包括不定参函数 )来获得一个 Stream 对象:

Stream<String> stream = Stream.of(array);
Stream<String> stream = Arrays.stream(array);
  • 如果你向通过集合对象来获得一个 Stream 对象:

Stream<String> stream = collection.stream();
Stream<String> stream = list.stream();
Stream<String> stream = set.stream();

1.1 获得 Stream 对象的其它方式。(可跳过)


1.1.1通过 Stream.generate(Supplier) 方法创建

配合 Stream#limit 方法使用
Stream<Double> stream = Stream.generate(Math::random).limit(10);

逻辑上,因为通过 Stream.generate 方法生成的 Stream 对象中的数据的数量是无限的 (即,你向 Stream 对象每次『要』一个对象时它都会每次生成一个返回给你,从而达到『无限个』的效果) ,所以,会结合 Stream#limit 方法来限定 stream 流中的数据总量。

1.1.2通过 Stream.iterator(Final T, final UnaryOperator<T> f) 方法创建

配合 Stream#limit 方法使用
Stream<Integer> stream = Stream.iterate(1, n -> n += 2);
// 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, ...

Stream.iterator 方法要求你提供 2 个参数:

  • 数据序列中的第一个数。这个数字需要使用者人为指定。通常也被称为『种子』。

  • 根据『前一个数字』计算『下一个数字』的计算规则。

整个序列的值就是:x, f(x), f(f(x)), f(f(f(x))), ...

逻辑上,因为通过 Stream.iterator 方法生成的 Stream 对象中的数据的数量是无限的 (即,你向 Stream 对象每次『要』一个对象时它都会每次生成一个返回给你,从而达到『无限个』的效果) ,所以,会结合 Stream#limit 方法来限定 stream 流中的数据总量。

  1. 中间操作:处理 Stream 中的数据序列

所谓的中间操作,指的就是对 Stream 中的数据使用流转换方法。

Stream#filter 和 Stream#map 方法是 Stream 最常见的 2 个流转换方法。另外,Stream#Match 方法也偶尔会遇到。

2.1 Stream#filter 方法:筛选出 ...

Stream#filter 是过滤转换,它将产生一个新的流,其中「包含符合某个特定条件」的所有元素。逻辑上就是「选中筛选出」的功能。

例如:

Stream<String> stream = Stream.of("hello", "world", "goodbye");
Stream<String> newStream = stream.filter( (item) -> item.startsWith("h") );
System.out.println( newStream.count() );  

Stream#filter 方法的参数是一个 Predicate<T> 对象,用于描述「选中」规则。

2.2 Stream#map 方法:形变

我们经常需要对一个 Stream 中的值进行某种形式的转换。这是可以考虑使用 Stream#map 方法,并传递给它一个负责进行转换的函数。

例如:

newStream = stream.map(String::toUpperCase);
  1. 数据收集

当经过第 2 步的操作之后,你肯定会需要收集 Stream 中(特别是 newStream 中,即,经过处理)的数据。

3.1 如果你想将数据收集到数组中:

Object[] array = newStream.toArray();

不过,无参的 Stream#toArray 方法返回的是一个 Object[] 数组。如果想获得一个正确类型的数组,可以将数组类型的构造函数传递给它:

String[] array = newStream.toArray(String[]::new);// 注意,这里是 String[] 而不是 String

3.2如果你想将数据收集到集合中:

collection = stream.collect(Collectors.toCollection())
      list = stream.collect(Collectors.toList());
       set = stream.collect(Collectors.toSet())

上述 3 个方法是原始的 Stream#collect 方法的简化。因为原始的、最底层的 Stream#collect 方法看起来比较『奇怪』。所以,我们通常不会直接使用它,而是使用上述 3 个简写来间接使用。

原始的 Stream#collect
list = stream.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
set = stream.collect(HashSet::new, HashSet::add, HashSet::addAll);

这里的第 1、第 2 个参数好理解,比较奇怪的是第 3 个参数。这里需要用到集合的 .addAll 方法是因为会将 Stream 中的数据先存放于多个集合中,最后再将多个集合合并成一个总的集合中再返回(这种『奇怪』的行为是和 Stream API 的并发特性有关)。

3.3如果你想将数据收集到 Map 中:

假设你有一个 Stream<Student>,并且你想将其中的元素收集到一个 map 中,这样你随后可以通过他们的 ID 来进行查找。为了实现这个目的,你可以在 Stream#collect 方法中使用 Collectors.toMap 。

Collectors.toMap 有 2 个函数参数,分别用来生成 map 的 key 和 value。例如:

Map<Integer,String> map = stream.collect(Collectors.toMap(Student::getId,Student::getName));

一般来说,Map 的 value 通常会是 Student 元素本身,这样的话可以实使用 Function.identity() 作为第 2 个参数,来实现这个效果(你可以将它视为固定用法)。

Map<Integer,Student> map = stream.collect(Collectors.toMap(Student::getId,Function.identity()));
  1. Stream#collect 其它功能

Stream#collect 方法除了上述的「可以将 Stream 对象中的数据提取到集合对象中」之外,还有其它的更多更丰富的功能。

提示
Stream#collect 方法经常会用到 java.util.stream.Collectors 类内置的静态方法。

4.1 Stream#collect 进行统计

Collectors 提供了一系列用于数据统计的静态方法:

#

方法

计数

count

平均值

averagingInt / averagingLong / averagingDouble

最值

maxBy / minBy

求和

summingInt / summingLong / summingDouble

统计以上所有

summarizingInt / summarizingLong / summarizingDouble

4.1.1统计计数:Stream#collect 利用 Collectors.count

String[] strArray = new String[] {"hello", "world", "good", "bye"};

log.info("{}", Stream.of(strArray).collect(Collectors.counting()));

如果你使用的是 IDEA ,通过 IDEA 的只能代码提示,你会发现 Stream 对象中有一个上述代码的简化版的计数方法 count() :

log.info("{}", Stream.of(arrays).count());

4.1.2求平均值:Stream#collect 利用 Collectors.averagingX

String[] strArray = new String[] {"hello", "world", "good", "bye"};

log.info("{}", Stream.of(strArray).collect(Collectors.averagingInt(String::length)));

4.1.3求极值:Stream#collect 利用 Collectors.maxBy 和 Collectors.minBy

String[] strArray = new String[] {"hello", "world", "good", "bye"};

log.info("{}", Stream.of(strArray).collect(Collectors.maxBy((o1, o2) -> o1.length() - o2.length())));
log.info("{}", Stream.of(strArray).collect(Collectors.minBy((o1, o2) -> o1.length() - o2.length())));

通过 IDEA 的代码提示功能,你会发现,上述代码有很大的简化空间:

// 保留 collect 方法和 Collectors 方法的前提下,可以简化成如下
log.info("{}", Stream.of(strArray).collect(Collectors.maxBy(Comparator.comparingInt(String::length))));
log.info("{}", Stream.of(strArray).collect(Collectors.minBy(Comparator.comparingInt(String::length))));

// 不保留 collect 方法和 Collectors 方法的情况下,可以进一步简化
log.info("{}", Stream.of(strArray).max(Comparator.comparingInt(String::length)));
log.info("{}", Stream.of(strArray).min(Comparator.comparingInt(String::length)));

4.1.4 统计求和:Stream#collect 利用 Collectors.summingX 进行统计求和

log.info("{}", Stream.of(strArray).collect(Collectors.summingInt(String::length)));

通过 IDEA 的代码提示功能,你会发现,上述代码可以简化:

log.info("{}", Stream.of(strArray).mapToInt(String::length).sum());

4.1.5一次性批量统计上述信息:Stream#collect 利用 Collectors.summarizingX 进行统计

Stream#collect 结合 Collectors.summarizingX 可以返回一个 XxxSummaryStatistics 对象,其中包含了上述的统计计数、平均值、极值等多项数据:

String[] strArray = new String[] {"hello", "world", "good", "bye"};

IntSummaryStatistics statistics = Stream.of(strArray).collect(Collectors.summarizingInt(String::length));
log.info("{}", statistics);

log.info("{}", statistics.getCount());
log.info("{}", statistics.getSum());
log.info("{}", statistics.getMin());
log.info("{}", statistics.getMax());
log.info("{}", statistics.getAverage());

4.2 Stream#collect 分组

Stream#collect 利用 Collectors.partitioningBy 方法或 Collectors#groupingBy 方法可以将 Stream 对象中的元素"按照你所提供的规则"分别提取到两个不同的 List 中。

String[] strArray = new String[] {"hello", "world", "good", "bye"};

log.info("{}", Stream.of(strArray).collect(Collectors.groupingBy(s -> s.length() % 2 == 0)));
log.info("{}", Stream.of(strArray).collect(Collectors.partitioningBy(s -> s.length() % 2 == 0)));

这两个方法返回的都是 Map<Boolean, List<T>> 对象,因此,你可以以 true 或 false 为键,分别从中拿到其中的某一部分数据。

另外,你可以连续多次分组,只需要嵌套使用 Collectors.groupingBy 或 CollectorspartitiongBy 方法。

 String[] strArray = new String[] {"hello", "world", "good", "bye"};

log.info("{}", Stream.of(strArray).collect(
    Collectors.partitioningBy(s -> s.length() % 2 == 0, 
        Collectors.partitioningBy(s -> s.length() > 3)
    )));

log.info("{}", Stream.of(strArray).collect(
      Collectors.groupingBy(s -> s.length() % 2 == 0, 
          Collectors.groupingBy(s -> s.length() > 3)
    )));

4.3 Stream#collect 拼接字符串

Stream#collect 利用 Collectors.joining 方法可以将 stream 中的元素用"你所指定的"连接符 (没有的话,则直接拼接) 拼接成一个字符串。

String[] strArray = new String[] {"hello", "world", "good", "bye"};

log.info("{}", Stream.of(strArray).collect(Collectors.joining()));
log.info("{}", Stream.of(strArray).collect(Collectors.joining("-")));
  1. Stream 对象的其它操作

5.1对 Stream 对象进行判断

Stream#anyMatch 、Stream#allMatch 、Stream#noneMatch 三个方法用于判断 Stream 中的元素是否『至少有一个』、『全部都』、『全部都不』满足某个条件。显而易见,这三个方法的返回值都是 boolean 值。

boolean b = stream.anyMatch((item) -> item.length() == 5);

5.2对 Stream 对象进行遍历

5.2.1Stream#forEach 遍历

Stream#filter 方法会遍历 Stream 中的每一个元素,对 Stream 中的每一个元素做一个操作,至于做何种操作,取决于使用者传递给 Stream#filter 的方法的参数 Consumer 对象。

例如:

Stream<String> stream = Stream.of("hello", "world", "goodbye");
stream.forEach(System.out::println);

5.2.2Stream#iterator 方法

Stream#iterator 方法会返回一个传统风格的迭代器,结合 Java SE 阶段的『集合框架』部分的知识点,通过 Iterator 对象你就可以遍历访问到 Stream 中的每一个元素。

newStream = ...;
Iterator<String> it = newStream.iterator();
while (it.hasNext()) {
    String str = it.next();
    System.out.println(str);
}

5.3对 Stream 对象进行排序

Stream#sorted 方法能实现对 stream 中的元素的排序。

它有两种排序:

  • Stream#sorted():自然排序,流中元素需实现 Comparable 接口

  • Stream#sorted(Comparator com):Comparator 排序器自定义排序

String[] strArray = new String[] {"hello", "world", "good", "bye"};

log.info("{}", Stream.of(strArray).sorted().collect(Collectors.toList()));

log.info("{}", Stream.of(strArray).sorted(Comparator.comparingInt(o -> o.charAt(1))).collect(Collectors.toList()));

log.info("{}", Stream.of(strArray).sorted(Comparator
        .comparingInt(String::length) // 先以字符串长度排序
        .thenComparingInt(value -> value.charAt(value.length()-1)) // 再以字符串最后一个字符大小排序
).collect(Collectors.toList()));

5.4对 Stream 对象进行合并和去重

流的合并使用 Stream.concat 方法;对流中的元素去重则使用 Stream#distinct 方法。

Stream<String> stream1 = Stream.of("a", "b", "c", "d");
Stream<String> stream2 = Stream.of("c", "d", "e", "f");

log.info("{}", Stream.concat(stream1, stream2).distinct().collect(Collectors.toList()));
  • 对 Stream 对象进行限定和跳过

限定指的是只从流中取出前 N 个数据以生成新的流对象,使用 Stream#limit 方法;跳过指的是忽略流中的前 N 个数据,取剩下的数据以生成新的流对象,使用 Stream#skip 方法。

Stream<String> stream1 = Stream.of("a", "b", "c", "d");
Stream<String> stream2 = Stream.of("c", "d", "e", "f");

log.info("{}", stream1.limit(2).collect(Collectors.toList()));
log.info("{}", stream2.skip(2).collect(Collectors.toList()));

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java 8引入了Stream API,它是一种函数式编程风格的API,可以帮助我们进行复杂的集合操作,以及实现并行处理等功能。本文将详细介绍Java Stream API的使用方法。 ## 什么是Stream Stream是Java 8中新增的一种数据处理方式,它可以让我们以声明式的方式对集合进行操作,而无需关心底层的实现细节。Stream可以让我们轻松地实现过滤、排序、映射、聚合等操作,而且可以支持并行处理,提高程序的运行效率。 Stream是一种惰性求值的操作,它只有在终止操作(Terminal Operation)被调用时才会开始执行中间操作(Intermediate Operation),这种设计可以让我们只对需要处理的元素进行操作,避免不必要的计算。 ## 使用Stream 使用Stream API,我们可以对集合进行一系列的操作,例如:过滤、排序、映射、聚合等。下面是一些常用的Stream操作: 1. 创建Stream对象 我们可以通过Collection.stream()或Collection.parallelStream()方法来创建Stream对象,例如: ```java List<String> list = Arrays.asList("a", "b", "c"); Stream<String> stream = list.stream(); ``` 2. 中间操作 中间操作是指对Stream对象进行的操作,例如:过滤、映射、排序等。常用的中间操作包括: - filter:过滤元素 - map:对元素进行映射 - sorted:对元素进行排序 - distinct:去重操作 - limit:限制元素数量 - skip:跳过元素 例如,我们可以通过filter()方法对Stream对象进行过滤操作: ```java List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); List<Integer> result = list.stream().filter(i -> i % 2 == 0).collect(Collectors.toList()); System.out.println(result); ``` 输出结果为: ``` [2, 4] ``` 在上面的代码中,我们首先创建了一个包含整数的List,然后使用stream()方法将List转换成Stream对象,接着使用filter()方法对元素进行过滤,最后使用collect()方法将Stream对象转换成List对象。 3. 终止操作 终止操作是指对Stream对象进行的最终操作,例如:收集、聚合等。常用的终止操作包括: - forEach:对每个元素执行操作 - collect:将元素收集到集合中 - reduce:对元素进行聚合操作 例如,我们可以通过reduce()方法对Stream对象进行聚合操作: ```java List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); Optional<Integer> result = list.stream().reduce((a, b) -> a + b); System.out.println(result.get()); ``` 输出结果为: ``` 15 ``` 在上面的代码中,我们首先创建了一个包含整数的List,然后使用stream()方法将List转换成Stream对象,接着使用reduce()方法对元素进行聚合操作,最后使用get()方法获取结果。 ## 并行流 Stream API还可以支持并行处理,可以通过parallel()方法将Stream对象转换为并行流,例如: ```java List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); int result = list.parallelStream().filter(i -> i % 2 == 0).mapToInt(i -> i).sum(); System.out.println(result); ``` 输出结果为: ``` 6 ``` 在上面的代码中,我们使用parallelStream()方法将List转换成并行流,接着使用filter()方法进行过滤操作,然后使用mapToInt()方法将元素映射为int类型,最后使用sum()方法对元素进行求和操作。 需要注意的是,并行流并不是万能的,它需要消耗额外的计算资源,而且在某些情况下可能会影响程序的性能。所以,在使用并行流时,需要根据具体的情况进行选择。 ## 总结 Java Stream API是一种非常强大的数据处理方式,它可以让我们以声明式的方式对集合进行操作,而无需关心底层的实现细节。使用Stream API,我们可以轻松地实现过滤、排序、映射、聚合等操作,而且可以支持并行处理,提高程序的运行效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值