Predicate 断定型接口
首先观察源码 只有一个方法test.该方法只有一个输入参数,返回值是一个布尔值 这类函数式接口通常成为断定型接口:有一个输入参数,返回值只能是布尔值
package java.util.function; import java.util.Objects; /** * Represents a predicate (boolean-valued function) of one argument. * * <p>This is a <a href="package-summary.html">functional interface</a> * whose functional method is {@link #test(Object)}. * * @param <T> the type of the input to the predicate * * @since 1.8 */ @FunctionalInterface public interface Predicate<T> { boolean test(T t); }
true
false
使用lambda表达式对函数式接口进行简化
Predicate<String> predicate=(str)->{return str.isEmpty();};
System.out.println(predicate.test("")); //true
- consumer 消费型接口 和supplier 供给型接口是相反的
观察源码发现,只有一个accept方法,只有一个输入参数,没有返回值 和供给型接口是相反的
package java.util.function; import java.util.Objects; /** * Represents an operation that accepts a single input argument and returns no * result. Unlike most other functional interfaces, {@code Consumer} is expected * to operate via side-effects. * * <p>This is a <a href="package-summary.html">functional interface</a> * whose functional method is {@link #accept(Object)}. * * @param <T> the type of the input to the operation * * @since 1.8 */ @FunctionalInterface public interface Consumer<T> { /** * Performs this operation on the given argument. * * @param t the input argument */ void accept(T t); }
package com.wyh.function; import java.util.function.Consumer; /** * @program: JUC * @description: consumer消费型接口和supplier供给型接口 * @author: 魏一鹤 * @createDate: 2022-03-06 15:46 **/ /** * Consumer函数式接口只有一个输入参数没有返回值 * * consumer消费型接口和supplier供给型接口是互相对应的 **/ public class demo03 { public static void main(String[] args){ Consumer<String> consumer = new Consumer<String>() { @Override public void accept(String o) { //打印字符串 System.out.println(o); } }; //调用方法 打印字符串 consumer.accept("wyh"); //wyh } }
wyh
使用lambda表达式对函数式接口进行简化
//lambda表达式简化代码 Consumer<String> consumer =(str)->{ System.out.println(str); }; consumer.accept("wyh"); //wyh
- supplier 供给型接口 consumer 消费型接口是相反的
首先观察源码 只有一个方法get,该方法只有没有参数,只有返回值 和消费型接口是相反的
@FunctionalInterface public interface Supplier<T> { /** * Gets a result. * * @return a result */ T get(); }
package com.wyh.function; /** * @program: JUC * @description: consumer消费型接口和supplier供给型接口 * @author: 魏一鹤 * @createDate: 2022-03-06 15:58 **/ import java.util.function.Supplier; /** * supplier供给型接口 没有参数 只有返回值 和consumer消费型接口是相反的 * **/ public class demo04 { public static void main(String[] args){ Supplier<Integer> supplier= new Supplier<Integer>() { @Override public Integer get() { //返回1024 return 1024; } }; //打印输出 supplier的get方法返回值 System.out.println(supplier.get()); //1024 } }
使用lambda表达式对函数式接口进行简化
//lambda表达式简化代码
Supplier<Integer> supplier=()->{return 1024;};
System.out.println(supplier.get()); //1024