Java8新特性—四大内置函数式接口( 三 )

执行结果:
这次消费了:100w元在双十一!这下穷死了!这次消费了:120w元在双十二!又穷死了!Consumer接口在JDK中的应用

Java8新特性—四大内置函数式接口

文章插图
同样的,我们以Stream中的forEach为例,看下面的例子:
Stream<Integer> stream = Stream.of(-1,0,1,2,3,4); stream.forEach(s-> System.out.println(s));执行结果:
-101234同样的我们还可以使用方法引用来打印,效果一致
stream.forEach(System.out::println);
对于方法引用不了解的亲,也可以阅读这篇文章Java8 新特性 - 方法引用@vchicken
3.Suppiler接口什么是Suppiler接口?既然我们上面说到了Consumer为消费型接口,按照惯例,那肯定有生产型接口或者也可以成为供给型接口——Supplier接口,看下图源码:
Java8新特性—四大内置函数式接口

文章插图
由源码我们可以看出,Supplier接口只有一个待实的get方法,属于无参有返回值的抽象方法 。下面看一个例子:
public static void main(String[] args) {// 生成一个字符串Supplier<String> supplier1 = () -> "abcde";// 生成一个随机数Supplier<Integer> supplier2 = () -> new Random().nextInt(10);// 产生一个运行时异常Supplier<RuntimeException> supplier3 = () -> new RuntimeException();System.out.println(supplier1.get());System.out.println(supplier2.get().intValue());System.out.println(supplier3.get());}执行结果:
abcde2java.lang.RuntimeExceptionSupplier接口在JDK中的应用
Java8新特性—四大内置函数式接口

文章插图
generate方法返回一个无限连续的无序流,其中每个元素由提供的供应商(Supplier)生成 。generate方法用于生成常量流和随机元素流 。看下面例子:
public static void main(String[] args) {// 生成随机数Stream.generate(() -> new Random().nextInt(10));stream.forEach(System.out::println);// 生成随机布尔流Stream.generate(() -> new Random().nextBoolean()).forEach(System.out::println);// 生成常量流Stream.generate(() -> "Hello World!").forEach(System.out::println);}执行结果:
251--- #略truefalsetrue--- #略Hello World!Hello World!Hello World!--- #略由于generate返回无限连续流,为了限制流中元素的数量,我们可以使用Stream.limit方法
public static void main(String[] args) { Stream.generate(() -> new Random().nextInt(10)).limit(3).forEach(e -> System.out.println(e)); Stream.generate(() -> new Random().nextBoolean()).limit(3).forEach(e -> System.out.println(e)); Stream.generate(() -> "Hello World!").limit(3).forEach(e -> System.out.println(e));}执行结果:
363truefalsefalseHello World!Hello World!Hello World!4.Predicate接口什么是Predicate接口?
Java8新特性—四大内置函数式接口

文章插图
Predicate接口又称为断言型接口,test()方法有参但是返回值类型是固定的boolean,看下面例子:
public static void main(String[] args) {Predicate<String> predicate = (s) -> s.length() > 0;// 测试字符串的长度是否>0System.out.println(predicate.test("hello"));// 结果取反System.out.println(predicate.negate().test("hello"));System.out.println("=====or / and======");System.out.println(predicate.test(""));// 增加或判断,二者满足其一则为trueSystem.out.println(predicate.or(s -> s.equals("")).test(""));// 增加与判断,二者都满足则为trueSystem.out.println(predicate.and(s -> s.equals("hello")).test(""));System.out.println(predicate.and(s -> s.equals("hello")).test("hello"));System.out.println("=====isEqual======");// 判断是否相等System.out.println(Predicate.isEqual("hello").test(""));System.out.println(Predicate.isEqual("hello").test("hello"));Predicate<Boolean> nonNull = Objects::nonNull;Predicate<Boolean> isNull = Objects::isNull;Predicate<String> isEmpty = String::isEmpty;Predicate<String> isNotEmpty = isEmpty.negate();}

经验总结扩展阅读