JAVA8 之 function 基礎

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接口的三個類型(兩個入參,一個出參)變成了同一個,所以就不單獨說了;

通過翻譯軟件得知。上面的接口大致的用途如下:

接口 入參 出參
BiConsumer T、U void
BiFunction T、U R
BiPredicate T、U boolean
Consumer T

void

Function T R
Predicate T boolean

小結:帶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,和我們的猜想正好吻合。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章