重复消费Java Stream的三种方法。你选择哪种?

山不在高水不在深 / 2023-07-21 / 原文

Java中的Stream一旦被消费就会关闭,不能再次使用了。如果的确有需要该怎么办呢?
这里介绍三种重复消费Stream的方法。

1. 从集合再次创建

这里你都不用往下继续看就知道该怎么办,不过我还是放上示例代码:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Stream<Integer> stream1 = numbers.stream();
Stream<Integer> stream2 = numbers.stream();

只需要分别消费每个stream就可以。

2. 通过Supplier多次创建

这种方法是大多数网文推荐的办法(他们只提供了这一种方法),比如

  • https://www.jb51.net/article/183920.htm
  • https://blog.csdn.net/SUDDEV/article/details/79380818
    我也贴一下示例代码:
Supplier<Stream<Integer>> supplier = () -> Stream.of(1, 2, 3, 4, 5);
Stream<Integer> stream1 = supplier.get();
Stream<Integer> stream2 = supplier.get();

同样地,你能拿到多个相同的stream。

3. 通过Stream Builder多次创建

这种方法用的最少,因为我们很少创建Builder:

IntStream.Builder builder = IntStream.builder();
builder.add(1);
builder.add(2);
builder.add(3);
builder.add(4);
builder.add(5);
IntStream stream1 = builder.build();
IntStream stream2 = builder.build();

建议

那么应该用哪种方法呢?第二种吗?NO!多数情况下应该是第一种。

Both approaches have their own advantages and disadvantages, and the choice between them depends on the specific use case.

Approach 1 (using a collection to create a new stream) is generally simpler and more efficient, especially if the original stream was created from a collection. Since the new stream is created from the same collection, there is no additional memory overhead or processing time required to create it.

Approach 2 (using a supplier to create a new stream) is more flexible, as it allows you to create a new stream from any source, not just a collection. However, it may be less efficient than approach 1, as creating a new stream from a non-collection source may require additional memory or processing time.

In general, if the original stream was created from a collection, approach 1 is recommended. If the original stream was created from a non-collection source, or if you need more flexibility in creating new streams, approach 2 may be more appropriate.