天天看點

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");