天天看点

Java 8之函数式编程(Function、Consumer、Supplier、Predicate)

1、Function

定义

public interface Function <T, R>
           

Represents a function that accepts one argument and produces a result.

(表明接受一个参数和产生一个结果的function)

T: the type of the input to the function(入参类型)

R: the type of the result of the function(出参类型)

调用函数

R apply(T t);
           

使用举例

// 入参+1
Function<Integer, Integer> incrFunc = p -> p + 1;

// ret=7
Integer ret = incrFunc.apply(6);
           

2、Consumer

定义

public interface Consumer<T>
           

Represent an operation that accepts a single input argument and returns no result

(表明接受一个参数无返回结果的operation,通常用于处理意外情况或额外动作)

T: the type of the input to the function(入参类型)

调用函数

void accept(T t);
           

使用举例

// 打印入参
Consumer<String> con1 = str -> system.out.println("处理内容:"+str);

con1.accept("hello!");
           

3、Supplier

定义

public interface Supplier<T>
           

Represents a supplier of results(只提供结果的supplier)

T: the type of results supplied by this supplier(结果类型)

调用函数

T get();
           

使用举例

// 获取字符串结果“hello!”
Supplier<String> supplier = () -> "hello!";

String ret = supplier.get();
           

4、Predicate

定义

public interface Predicate<T>
           

Represents a predicate(boolean-value function) of one argument(代表一个带一个入参的断言-boolean值函数)

T:the type of input to the predicate(入参)

调用方法

boolean test(T t);
           

使用举例

// 获取字符串等于“hello!”
Predicate<String> predicate = str -> str.equals("hello!");

// ret=false
boolean ret = predicate.test("hheee");