Function / BiFunction / Consumer / Supplier的区别:

6 阅读2分钟

一、总览一句话口诀(背这个就够)

  1. Supplier无参数,有返回值 (我造东西给你)
  2. Consumer有参数,无返回值 (你给我东西,我消费掉)
  3. Function1 个参数,有返回值 (你给我一个,我加工还给你)
  4. BiFunction2 个参数,有返回值 (你给我两个,我加工还给你)

二、超级对比图(文字版高清,直接存)

接口入参个数是否有返回值核心方法大白话含义你项目真实用过场景
Supplier0 个✅ 有返回 TT get()无中生有我不需要任何东西,直接生成对象给你懒加载创建对象、提供实例
Consumer1 个❌ 无返回 voidvoid accept(T t)只收不用还你给我一个对象,我处理完就结束,不返回你之前 Consumer<Fragment>、路由回调、拿到 Fragment 做操作
Function<T,R>1 个✅ 有返回 RR apply(T t)一进一出传入 1 个参数,加工处理,返回新结果参数转换、数据映射、类型转换
BiFunction<T,U,R>2 个✅ 有返回 RR apply(T t, U u)两进一出传入 2 个参数,加工处理,返回新结果你现在这段 Navigation 代码!BiFunction<Fragment, Integer, NavDestination>传入Fragment+容器id,返回导航Destination

三、源码原生定义(一眼看懂结构)

1. Supplier(无参,有返回)

java

运行

@FunctionalInterface
public interface Supplier<T> {
    T get();
}

2. Consumer(单参,无返回)

java

运行

@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
}

3. Function(单参,有返回)

java

运行

@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);
}

4. BiFunction(双参,有返回)

java

运行

@FunctionalInterface
public interface BiFunction<T, U, R> {
    R apply(T t, U u);
}

四、每个接口最简单 Demo 代码(复制就能跑)

1. Supplier 无参,有返回

java

运行

// 不需要传参数,直接返回一个字符串
Supplier<String> supplier = () -> "我生成的内容";
String result = supplier.get();

2. Consumer 单参,无返回

java

运行

// 传入一个字符串,只打印,不返回任何东西
Consumer<String> consumer = str -> System.out.println(str);
consumer.accept("接收并消费");

3. Function 1 参入,1 参出

java

运行

// 传入数字,返回平方
Function<Integer, Integer> function = a -> a * a;
Integer result = function.apply(5); // 25

4. BiFunction 2 参入,1 参出

java

运行

// 传入两个数字,返回相加结果
BiFunction<Integer, Integer, Integer> biFunction = (a, b) -> a + b;
Integer result = biFunction.apply(5, 3); // 8

五、结合你所有写过的代码,逐个对应(最重要)

1)你之前问的 Consumer<Fragment>

java

运行

Consumer<Fragment> consumer = fragment -> {
    // 拿到fragment,做各种操作
    // 没有返回值
};
consumer.accept(fragment);

给我一个 Fragment,我处理,不返回

2)你现在 Navigation 项目代码 BiFunction

java

运行

BiFunction<Fragment, Integer, NavDestination> func
= (fragment, containerId) -> {
    // 传入 父Fragment + 容器id
    // 返回 创建好的 NavDestination
    return destination;
};

// 管理器内部调用
NavDestination dest = func.apply(fragment, containerId);

两个参数进来,一个结果出去

六、超精简速记口诀(面试必背)

  • Supplier无入,有出

  • Consumer有入,无出

  • Function一入,一出

  • BiFunction两入,一出