A sequence of elements supporting sequential and parallel aggregate operations.

Stream 的定义可以看出

  • Stream 是一组元素的集合
  • Stream 支持顺序和并行地对元素进行操作

How it work

先看示例:

1
2
3
4
5
6
7
8
public void method1() {
List<String> list = Stream.of("a", "b", "c", 1, 2, 3)
.peek(System.out::print)
.map(String::valueOf)
.sorted()
.collect(Collectors.toList());
System.out.println("\n" + JSON.toJSONString(list));
}

上述程序输出结果:

1
2
abc123
["1","2","3","a","b","c"]

通过上述例子:

  1. Stream.of() 产生一个流;
  2. peek 将所有元素进行打印;
  3. map 将所有元素转化为 String;
  4. sorted 将所有元素进行排序;
  5. collect 将所有元素聚合为一个 List。
阅读全文 »