Java 8 新特性之 Stream

  • Stream 接口

Stream

Stream 由三部分构成

  1. 零个或多个中间操作 (返回 Stream )
  2. 终止操作

Stream 操作分类

  1. 惰性求值
  2. 及早求值

Stream 对象创建

  1. 通过静态方法创建
1
2
3
4
Stream stream1 = Stream.of("hello", "kitty", "hello kitty");

String[] myArray = new String[] {"hello", "kitty", "hello kitty");
Stream stream2 = Stream.of(myArray);
  1. 通过 Arrays 的方法创建
1
2
String[] myArray = new String[] {"hello", "kitty", "hello kitty");
Stream stream = Arrays.stream(myArray);
  1. 通过 List 的 stream 方法创建
1
2
List<String> list = Arrays.asList("hello", "kitty", "hello kitty");
Stream stream = list.stream();

Stream 类型转换

  1. 通过 Stream 的 toArray 方法, 将 String Stream 转换成 String 数组
1
2
3
Stream<String> stream = Stream.of ( "hello", "kitty", "hello kitty" );
String[] strings = stream.toArray (l -> new String[l] );
//String[] strings = stream.toArray(new String[]);
  1. 通过 Stream 的 collect 方法, 将 Stream 转换为 List
1
2
Stream<String> stream = Stream.of ( "hello", "kitty", "hello kitty" );
List<String> strings = stream.collect( Collectors.toList());

collect 还有另一种重载方法

1
2
3
<R> R collect(Supplier<R> supplier,
BiConsumer<R, ? super T> accumulator,
BiConsumer<R, R> combiner);

应该可以理解为:

supplier 创建一个新 List
accumulator 把 Stream 每个内容加入进 List
把 List 的值转移到当前 List (我们需要的 List)


1
2
3
Stream<String> stream = Stream.of ( "hello", "kitty", "hello kitty" );
LinkedList<String> strings = stream.collect ( () -> new LinkedList<String> (), (a, b) -> a.add ( b ), (a, b) -> a.addAll ( b ) );
//List<String> strings = stream.collect ( LinkedList::new, LinkedList::add, LinkedList::addAll );

------ end ------