当前位置:首页 > JAVA教程 > JAVA基础

Java 9 改进的 Stream API

java 9 改进的 stream api

java 9 改进的 stream api 添加了一些便利的方法,使流处理更容易,并使用收集器编写复杂的查询。

java 9 为 stream 新增了几个方法:dropwhile、takewhile、ofnullable,为 iterate 方法新增了一个重载方法。

takewhile 方法

语法

default stream<t> takewhile(predicate<? super t> predicate)

takewhile() 方法使用一个断言作为参数,返回给定 stream 的子集直到断言语句第一次返回 false。如果第一个值不满足断言条件,将返回一个空的 stream。

takewhile() 方法在有序的 stream 中,takewhile 返回从开头开始的尽量多的元素;在无序的 stream 中,takewhile 返回从开头开始的符合 predicate 要求的元素的子集。

实例

import java.util.stream.stream; public class tester { public static void main(string[] args) { stream.of("a","b","c","","e","f").takewhile(s->!s.isempty()) .foreach(system.out::print); } }

以上实例 takewhile 方法在碰到空字符串时停止循环输出,执行输出结果为:

abc
dropwhile 方法

语法

default stream<t> dropwhile(predicate<? super t> predicate)

dropwhile 方法和 takewhile 作用相反的,使用一个断言作为参数,直到断言语句第一次返回 false 才返回给定 stream 的子集。

实例

import java.util.stream.stream; public class tester { public static void main(string[] args) { stream.of("a","b","c","","e","f").dropwhile(s-> !s.isempty()) .foreach(system.out::print); } }

以上实例 dropwhile 方法在碰到空字符串时开始循环输出,执行输出结果为:

ef
iterate 方法

语法

static <t> stream<t> iterate(t seed, predicate<? super t> hasnext, unaryoperator<t> next)

方法允许使用初始种子值创建顺序(可能是无限)流,并迭代应用指定的下一个方法。 当指定的 hasnext 的 predicate 返回 false 时,迭代停止。

实例

java.util.stream.intstream; public class tester { public static void main(string[] args) { intstream.iterate(3, x -> x < 10, x -> x+ 3).foreach(system.out::println); } }

执行输出结果为:

3
6
9
ofnullable 方法

语法

static <t> stream<t> ofnullable(t t)

ofnullable 方法可以预防 nullpointerexceptions 异常, 可以通过检查流来避免 null 值。

如果指定元素为非 null,则获取一个元素并生成单个元素流,元素为 null 则返回一个空流。

实例

import java.util.stream.stream; public class tester { public static void main(string[] args) { long count = stream.ofnullable(100).count(); system.out.println(count); count = stream.ofnullable(null).count(); system.out.println(count); } }

执行输出结果为:

1
0

【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐