Function 介绍

函数型接口,接收 T 对象,返回 R 对象。

使用示例

public class Test {
    public static void main(String args[]) {
        Function<Integer, String> f1 = (score)->{
            if(score > 90) {
                return "666,我滴宝贝!";
            } else {
                return "死狗,滚!";
            }
        };
        System.out.println(f1.apply(91));
    }
}

结果:
666,我滴宝贝!

Function 源码

package java.util.function;
import java.util.Objects;

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

    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }

    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }

    static <T> Function<T, T> identity() {
        return t -> t;
    }
}

相关文章: