Java8的Stream
在Java8中,一个比较大的变化就是流(Stream),具体可以看之前的一篇文章:
Java9的Stream
Java9中Stream增加了4个方法,分别是:
takeWhile
:在有序的Stream中,takeWhile返回从开头开始的尽量多的元素
default StreamtakeWhile(Predicate predicate) { Objects.requireNonNull(predicate); // Reuses the unordered spliterator, which, when encounter is present, // is safe to use as long as it configured not to split return StreamSupport.stream( new WhileOps.UnorderedWhileSpliterator.OfRef.Taking<>(spliterator(), true, predicate), isParallel()).onClose(this::close);}复制代码
dropWhile
:与takeWhile
相反
default StreamdropWhile(Predicate predicate) { Objects.requireNonNull(predicate); // Reuses the unordered spliterator, which, when encounter is present, // is safe to use as long as it configured not to split return StreamSupport.stream( new WhileOps.UnorderedWhileSpliterator.OfRef.Dropping<>(spliterator(), true, predicate), isParallel()).onClose(this::close);}复制代码
- ofNullable:可以创建一个单元素Stream,可以为null
public staticStream ofNullable(T t) { return t == null ? Stream.empty() : StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);}复制代码
- iterate
public staticStream iterate(final T seed, final UnaryOperator f) { Objects.requireNonNull(f); Spliterator spliterator = new Spliterators.AbstractSpliterator<>(Long.MAX_VALUE, Spliterator.ORDERED | Spliterator.IMMUTABLE) { T prev; boolean started; @Override public boolean tryAdvance(Consumer action) { Objects.requireNonNull(action); T t; if (started) t = f.apply(prev); else { t = seed; started = true; } action.accept(prev = t); return true; } }; return StreamSupport.stream(spliterator, false);}复制代码
除了对 Stream 本身的扩展,Optional和Stream之间的结合也得到了改进,可以将optional对象转化为stream对象:
Listlist = new ArrayList<>() { { add("a");add("b");add("c");}};Optional
> optional = Optional.ofNullable(list);Stream
> stream = optional.stream();stream.flatMap(x -> x.stream()).forEach(System.out::println);复制代码
使用举例
- takeWhile
Listlist = Arrays.asList(1, 4, 5, 2, 3, 6, 7, 8, 9, 10);list.stream().takeWhile(x -> x < 5).forEach(System.out::println);复制代码
输出:
14
- dropWhile
Listlist = Arrays.asList(1, 4, 5, 2, 3, 6, 7, 8, 9, 10);list.stream().dropWhile(x -> x < 5).forEach(System.out::println);复制代码
输出:
523678910
- ofNullable
Streamstream = Stream.of("", null);System.out.println(stream.count());Stream stream = Stream.of(null);System.out.println(stream.count());//会抛空指针异常Stream stream = Stream.ofNullable(null);System.out.println(stream.count());复制代码
输出:
20
- iterate
//java8Stream.iterate(1, i -> i + 1).limit(5).forEach(System.out::println);//java9Stream.iterate(1, i -> i < 6, i -> i + 1).forEach(System.out::println);复制代码
输出:
12345