Stream的创建方式有很多种,除了最常见的集合创建,还有其他几种方式。

List转Stream

List继承自Collection接口,而Collection提供了stream()方法。

1
2
3
List<Integer> list = Lists.newArrayList(1, 2, 3);
Stream<Integer> stream = list.stream();

数组转stream

对于数组,Arrays提供了stream()方法。

1
2
String[] arr = new String[]{"a", "b", "c"};
Stream<String> stream = Arrays.stream(arr);

Map转stream

Map并不是一个序列,不是集合,没办法直接转成stream(). 但entrySet()是Set,可以转

1
2
3

Map<String, Object> map = Maps.newHashMap();
Stream<Entry<String, Object>> stream = map.entrySet().stream();

直接创建Stream

Stream也提供了API直接生成一个Stream,这个Stream大概可以理解成一个List。因为内部就是数组实现的。

1
Stream<Integer> integerStream = Stream.of(1, 2, 3);

读取文件的Stream

用过Linux的就会对其命令行的管道符敬佩不已,一个管道符就可以源源不断的做处理。在Java里读取文件也可以实现类似的功能。

1
2
3
4
5
6
7
8
9

long uniqueWords = 0;
try (Stream<String> lines = Files.lines(Paths.get("data.txt"), Charset.defaultCharset())) {
uniqueWords = lines.flatMap(l -> Arrays.stream(l.split(" ")))
.distinct()
.count();
} catch (IOException e) {
//
}

通过函数来生成无限流

Stream提供了iterate来生成一个无限序列,一个基于初始值的无限序列。可以用lambda设置序列的生成规则,比如每次增加2.

1
2
3
4
Stream.iterate(0, n -> n + 2)
.limit(10)
.forEach(System.out::println);

再比如,斐波那契数列(Fibonacci sequence)

1
2
3
4
5

Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1], t[0] + t[1]})
.limit(20)
.map(t -> t[0])
.forEach(System.out::println);

Stream还提供了另一个generate方法来生成序列。接收一个用户指定的生成序列函数IntSupplier.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
IntSupplier fib = new IntSupplier() {
private int previous = 0;
private int current = 1;

@Override
public int getAsInt() {
int oldPrevious = this.previous;
int nextValue = this.previous + this.current;
this.previous = this.current;
this.current = nextValue;
return oldPrevious;
}
};
IntStream.generate(fib).limit(10).forEach(System.out::println);