JAVA8 之 function 基础

    技术2025-09-28  36

    function 包简介

    在java8中新引入了一个包

    这是一个重要的更新,牵扯到了lamada表达式和一系列的语法结构变动。

    function包主要有六个比较重要的interface;

    按照字典排序 /** * Represents an operation that accepts two input arguments and returns no * result. This is the two-arity specialization of {@link Consumer}. * Unlike most other functional interfaces, {@code BiConsumer} is expected * to operate via side-effects. */ interface BiConsumer<T, U> /** * Represents a function that accepts two arguments and produces a result. * This is the two-arity specialization of {@link Function}. */ interface BiFunction<T, U, R> /** * Represents a predicate (boolean-valued function) of two arguments. This is * the two-arity specialization of {@link Predicate}. */ interface BiPredicate<T, U> /** * Represents an operation that accepts a single input argument and returns no * result. Unlike most other functional interfaces, {@code Consumer} is expected * to operate via side-effects. */ interface Consumer<T> /** * Represents a function that accepts one argument and produces a result. */ interface Function<T, R> /** * Represents a predicate (boolean-valued function) of one argument. */ interface Predicate<T>

    其实还有几个家伙:如  

    interface BinaryOperator<T> extends BiFunction<T,T,T>

    因为该家伙就是继承的 function接口,把function接口的三个类型(两个入参,一个出参)变成了同一个,所以就不单独说了;

    通过翻译软件得知。上面的接口大致的用途如下:

    接口入参出参BiConsumerT、UvoidBiFunctionT、URBiPredicateT、UbooleanConsumerT

    void

    FunctionTRPredicateTboolean

    小结:带BI的多一个入参。

     

    例一:

    借用上一篇文章的内容,我们在调用Collectors.toMap的时候 最后一个参数内容 为 

    (u, v) -> v studentList.stream().collect(Collectors.toMap(Student::getAge, Student::getName, (u, v) -> v));

    这里如果使用idea,我们ctrl+鼠标左键可以看到父类就是 

    interface BinaryOperator<T> extends BiFunction<T,T,T>

    因为该方法满足两个入参+一个出参,同时我们看到toMap中的源码如下

    public static <T, K, U> Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, BinaryOperator<U> mergeFunction) { return toMap(keyMapper, valueMapper, mergeFunction, HashMap::new); }

    就是使用的 

    BinaryOperator<U>

    那么问题来了,我们怎么知道 

    (u, v) -> v

    哪个是map的旧值,哪个是新值呢?我们到hashmap中的源码查看如下

    发现前面的为旧值,后面的为新值。

    例二:

    我们再看一个例子

    这里的 (k,v) 正好满足我们的BiConsumer ,两个入参,没有出参。我们点进去验证一下

    foreach的源码入参正好就是biconsumer,和我们的猜想正好吻合。

     

     

    Processed: 0.009, SQL: 9