Functional Programming With Java 简明教程

Functional Programming - Infinite Streams

集合是内存中数据结构,其中包含集合中存在的所有元素,并且我们有外部迭代来遍历集合,而流是按需计算元素的固定数据结构,并且流具有内部迭代来遍历每个元素。以下示例演示如何从数组创建流。

Collections are in-memory data structure which have all the elements present in the collection and we have external iteration to iterate through collection whereas Stream is a fixed data structure where elements are computed on demand and a Stream has inbuilt iteration to iterate through each element. Following example shows how to create a Stream from an array.

int[] numbers = {1, 2, 3, 4};
IntStream numbersFromArray = Arrays.stream(numbers);

上面的流具有固定大小,由四个数字数组构成,并且在第四个元素后不会返回元素。但是,我们可以使用 Stream.iterate() 或 Stream.generate() 方法创建流,该方法可以有将传递到流的 lambda 表达式。使用 lambda 表达式,我们可以传递在满足某个条件后给定所需元素的条件。考虑一种情况,我们需要一个包含 3 的倍数的数字列表。

Above stream is of fixed size being built from an array of four numbers and will not return element after 4th element. But we can create a Stream using Stream.iterate() or Stream.generate() method which can have lamdba expression will pass to a Stream. Using lamdba expression, we can pass a condition which once fulfilled give the required elements. Consider the case, where we need a list of numbers which are multiple of 3.

Example - Infinite Stream

import java.util.stream.Stream;

public class FunctionTester {
   public static void main(String[] args) {
      //create a stream of numbers which are multiple of 3
      Stream<Integer> numbers = Stream.iterate(0, n -> n + 3);

      numbers
         .limit(10)
         .forEach(System.out::println);
   }
}

Output

0
3
6
9
12
15
18
21
24
27

为了对无限流进行操作,我们使用流接口的 limit() 方法来限制在数字计数变为 10 时的数字迭代。

In order to operate on infinite stream, we’ve used limit() method of Stream interface to restrict the iteration of numbers when their count become 10.