侧边栏壁纸
博主头像
牧云

怀璧慎显,博识谨言。

  • 累计撰写 88 篇文章
  • 累计创建 9 个标签
  • 累计收到 8 条评论

目 录CONTENT

文章目录

Java函数式接口

秋之牧云
2025-11-19 / 0 评论 / 0 点赞 / 8 阅读 / 0 字

一、java.util.function 包中的函数式接口定义


1. Function<T, R>

@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);
}
  • 作用:将一个类型 T 转换为另一个类型 R

  • 示例String -> Integer


2. Consumer<T>

@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
}
  • 作用:对一个输入值进行消费(不返回结果)。

  • 示例String -> void


3. Supplier<T>

@FunctionalInterface
public interface Supplier<T> {
    T get();
}
  • 作用:提供一个值,不接受参数。

  • 示例void -> String


4. Predicate<T>

@FunctionalInterface
public interface Predicate<T> {
    boolean test(T t);
}
  • 作用:对一个输入值进行判断,返回布尔值。

  • 示例Integer -> boolean


5. UnaryOperator<T>

@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, T> {
    T apply(T t);
}
  • 作用:对一个输入值进行操作并返回相同类型的输出。

  • 示例String -> String


6. BinaryOperator<T>

@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T, T, T> {
    T apply(T t1, T t2);
}
  • 作用:对两个同类型输入值进行操作并返回同类型结果。

  • 示例Integer + Integer -> Integer


7. BiFunction<T, U, R>

@FunctionalInterface
public interface BiFunction<T, U, R> {
    R apply(T t, U u);
}
  • 作用:对两个不同类型的输入值进行处理,返回一个结果。

  • 示例String, Integer -> String


8. BiConsumer<T, U>

@FunctionalInterface
public interface BiConsumer<T, U> {
    void accept(T t, U u);
}
  • 作用:对两个输入值进行消费(不返回结果)。

  • 示例String, Integer -> void


9. BiPredicate<T, U>

@FunctionalInterface
public interface BiPredicate<T, U> {
    boolean test(T t, U u);
}
  • 作用:对两个输入值进行判断,返回布尔值。

  • 示例String, Integer -> boolean


二、其他常用函数式接口(如 Runnable, Callable 等)

虽然这些不是 java.util.function 包的一部分,但它们也是常见的函数式接口:

10. Runnable

@FunctionalInterface
public interface Runnable {
    void run();
}
  • 作用:无参数、无返回值的函数式接口。

  • 示例void -> void


11. Callable<V>

@FunctionalInterface
public interface Callable<V> {
    V call() throws Exception;
}
  • 作用:执行任务并返回结果,可能抛出异常。

  • 示例void -> Object


三、总结

接口名称

参数个数

返回值

是否继承自其他接口

示例

Function<T, R>

1

R

String -> Integer

Consumer<T>

1

void

String -> void

Supplier<T>

0

T

void -> String

Predicate<T>

1

boolean

Integer -> boolean

UnaryOperator<T>

1

T

Function<T, T>

String -> String

BinaryOperator<T>

2

T

BiFunction<T, T, T>

Integer + Integer -> Integer

BiFunction<T, U, R>

2

R

String, Integer -> String

BiConsumer<T, U>

2

void

String, Integer -> void

BiPredicate<T, U>

2

boolean

String, Integer -> boolean

Runnable

0

void

void -> void

Callable<V>

0

V

void -> Object

0

评论区