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

时间:2025-02-15 21:07:58

1、Function

定义
public interface Function <T, R>
  • 1

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
使用举例
// 入参+1
Function<Integer, Integer> incrFunc = p -> p + 1;

// ret=7
Integer ret = (6);
  • 1
  • 2
  • 3
  • 4
  • 5

2、Consumer

定义
public interface Consumer<T>
  • 1

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);
  • 1
使用举例
// 打印入参
Consumer<String> con1 = str -> ("处理内容:"+str);

("hello!");
  • 1
  • 2
  • 3
  • 4

3、Supplier

定义
public interface Supplier<T>
  • 1

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

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

调用函数
T get();
  • 1
使用举例
// 获取字符串结果“hello!”
Supplier<String> supplier = () -> "hello!";

String ret = ();
  • 1
  • 2
  • 3
  • 4

4、Predicate

定义
public interface Predicate<T>
  • 1

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

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

调用方法
boolean test(T t);
  • 1
使用举例
// 获取字符串等于“hello!”
Predicate<String> predicate = str -> ("hello!");

// ret=false
boolean ret = ("hheee");
  • 1
  • 2
  • 3
  • 4
  • 5