java stream 2 函數(shù)式接口

函數(shù)式接口是伴隨著Stream的誕生而出現(xiàn)的,Java8Stream 作為函數(shù)式編程的一種具體實現(xiàn)棺禾,開發(fā)者無需關(guān)注怎么做读处,只需知道要做什么,各種操作符配合簡潔明了的函數(shù)式接口給開發(fā)者帶來了簡單快速處理數(shù)據(jù)的體驗猜惋。

函數(shù)式接口

什么是函數(shù)式接口丸氛?簡單來說就是只有一個抽象函數(shù)的接口。為了使得函數(shù)式接口的定義更加規(guī)范著摔,java8 提供了@FunctionalInterface 注解告訴編譯器在編譯器去檢查函數(shù)式接口的合法性缓窜,以便在編譯器在編譯出錯時給出提示。為了更加規(guī)范定義函數(shù)接口谍咆,給出如下函數(shù)式接口定義規(guī)則:

  • 有且僅有一個抽象函數(shù)
  • 必須要有@FunctionalInterface 注解
  • 可以有默認方法

可以看出函數(shù)式接口的編寫定義非常簡單禾锤,不知道大家有沒有注意到,其實我們經(jīng)常會用到函數(shù)式接口摹察,如Runnable 接口恩掷,它就是一個函數(shù)式接口:

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

過去我們會使用匿名內(nèi)部類來實現(xiàn)線程的執(zhí)行體:

new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello FunctionalInterface");
            }
        }).start();

現(xiàn)在我們使用Lambda 表達式,這里函數(shù)式接口的使用沒有體現(xiàn)函數(shù)式編程思想供嚎,這里輸出字符到標準輸出流中螃成,產(chǎn)生了副作用,起到了簡化代碼的作用查坪,當然還有裝B。

 new Thread(()->{
            System.out.println("Hello FunctionalInterface");
        }).start();

Java8 util.function 包下自帶了43個函數(shù)式接口宁炫,大體分為以下幾類:

  • Consumer 消費接口
  • Function 功能接口
  • Operator 操作接口
  • Predicate 斷言接口
  • Supplier 生產(chǎn)接口

其他接口都是在此基礎(chǔ)上變形定制化罷了偿曙。

函數(shù)式接口詳細介紹

這里只介紹最基礎(chǔ)的函數(shù)式接口,至于它的變體只要明白了基礎(chǔ)自然就能夠明白

Consumer

消費者接口羔巢,就是用來消費數(shù)據(jù)的望忆。

@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);

    /**
     * Returns a composed {@code Consumer} that performs, in sequence, this
     * operation followed by the {@code after} operation. If performing either
     * operation throws an exception, it is relayed to the caller of the
     * composed operation.  If performing this operation throws an exception,
     * the {@code after} operation will not be performed.
     *
     * @param after the operation to perform after this operation
     * @return a composed {@code Consumer} that performs in sequence this
     * operation followed by the {@code after} operation
     * @throws NullPointerException if {@code after} is null
     */
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

Consumer 接口中有accept 抽象方法罩阵,accept接受一個變量,也就是說你在使用這個函數(shù)式接口的時候启摄,給你提供了數(shù)據(jù)稿壁,你只要接收使用就可以了;andThen 是一個默認方法歉备,接受一個Consumer 類型傅是,當你對一個數(shù)據(jù)使用一次還不夠爽的時候,你還能再使用一次蕾羊,當然你其實可以爽無數(shù)次喧笔,只要一直使用andThan方法。


Function

何為Function呢龟再?比如電視機书闸,給你帶來精神上的愉悅,但是它需要用電啊利凑,電視它把電轉(zhuǎn)換成了你荷爾蒙浆劲,這就是Function,簡單電說哀澈,F(xiàn)unction 提供一種轉(zhuǎn)換功能牌借。

@FunctionalInterface
public interface Function<T, R> {

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);

    /**
     * Returns a composed function that first applies the {@code before}
     * function to its input, and then applies this function to the result.
     * If evaluation of either function throws an exception, it is relayed to
     * the caller of the composed function.
     *
     * @param <V> the type of input to the {@code before} function, and to the
     *           composed function
     * @param before the function to apply before this function is applied
     * @return a composed function that first applies the {@code before}
     * function and then applies this function
     * @throws NullPointerException if before is null
     *
     * @see #andThen(Function)
     */
    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }

    /**
     * Returns a composed function that first applies this function to
     * its input, and then applies the {@code after} function to the result.
     * If evaluation of either function throws an exception, it is relayed to
     * the caller of the composed function.
     *
     * @param <V> the type of output of the {@code after} function, and of the
     *           composed function
     * @param after the function to apply after this function is applied
     * @return a composed function that first applies this function and then
     * applies the {@code after} function
     * @throws NullPointerException if after is null
     *
     * @see #compose(Function)
     */
    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }

    /**
     * Returns a function that always returns its input argument.
     *
     * @param <T> the type of the input and output objects to the function
     * @return a function that always returns its input argument
     */
    static <T> Function<T, T> identity() {
        return t -> t;
    }
}

Function 接口 最主要的就是apply 函數(shù),apply 接受T類型數(shù)據(jù)并返回R類型數(shù)據(jù)日丹,就是將T類型的數(shù)據(jù)轉(zhuǎn)換成R類型的數(shù)據(jù)走哺,它還提供了compose、andThen哲虾、identity 三個默認方法丙躏,compose 接受一個Function,andThen也同樣接受一個Function束凑,這里的andThen 與Consumer 的andThen 類似晒旅,在apply之后在apply一遍,compose 則與之相反汪诉,在apply之前先apply(這兩個apply具體處理內(nèi)容一般是不同的)废恋,identity 起到了類似海關(guān)的作用,外國人想要運貨進來扒寄,總得交點稅吧鱼鼓,然后貨物才能安全進入中國市場,當然了想不想收稅還是你說了算的:该编。


Operator

可以簡單理解成算術(shù)中的各種運算操作迄本,當然不僅僅是運算這么簡單,因為它只定義了運算這個定義课竣,但至于運算成什么樣你說了算嘉赎。由于沒有最基礎(chǔ)的Operator置媳,這里將通過 BinaryOperator、IntBinaryOperator來理解Operator 函數(shù)式接口公条,先從簡單的IntBinaryOperator開始拇囊。

IntBinaryOperator

從名字可以知道,這是一個二元操作靶橱,并且是Int 類型的二元操作寥袭,那么這個接口可以做什么呢,除了加減乘除抓韩,還可以可以實現(xiàn)平方(兩個相同int 數(shù)操作起來不就是平方嗎)纠永,還是先看看它的定義吧:

@FunctionalInterface
public interface IntBinaryOperator {

    /**
     * Applies this operator to the given operands.
     *
     * @param left the first operand
     * @param right the second operand
     * @return the operator result
     */
    int applyAsInt(int left, int right);
}

IntBinaryOperator 接口內(nèi)只有一個applyAsInt 方法,其接收兩個int 類型的參數(shù)谒拴,并返回一個int 類型的結(jié)果尝江,其實這個跟Function 接口的apply 有點像,但是這里限定了英上,只能是int類型炭序。

BinaryOperator

BinaryOperator 二元操作,看起來它和IntBinaryOperator 是父子關(guān)系苍日,實際上這兩者沒有半點關(guān)系惭聂,但他們在功能上還是有相似之處的:

@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T,T,T> {
    /**
     * Returns a {@link BinaryOperator} which returns the lesser of two elements
     * according to the specified {@code Comparator}.
     *
     * @param <T> the type of the input arguments of the comparator
     * @param comparator a {@code Comparator} for comparing the two values
     * @return a {@code BinaryOperator} which returns the lesser of its operands,
     *         according to the supplied {@code Comparator}
     * @throws NullPointerException if the argument is null
     */
    public static <T> BinaryOperator<T> minBy(Comparator<? super T> comparator) {
        Objects.requireNonNull(comparator);
        return (a, b) -> comparator.compare(a, b) <= 0 ? a : b;
    }

    /**
     * Returns a {@link BinaryOperator} which returns the greater of two elements
     * according to the specified {@code Comparator}.
     *
     * @param <T> the type of the input arguments of the comparator
     * @param comparator a {@code Comparator} for comparing the two values
     * @return a {@code BinaryOperator} which returns the greater of its operands,
     *         according to the supplied {@code Comparator}
     * @throws NullPointerException if the argument is null
     */
    public static <T> BinaryOperator<T> maxBy(Comparator<? super T> comparator) {
        Objects.requireNonNull(comparator);
        return (a, b) -> comparator.compare(a, b) >= 0 ? a : b;
    }
}

BinaryOperator 是 BiFunction 生的,而IntBinaryOperator 是從石頭里蹦出來的相恃,BinaryOperator 自身定義了minBy辜纲、maxBy默認方法,并且參數(shù)都是Comparator拦耐,就是根據(jù)傳入的比較器的比較規(guī)則找出最小最大的數(shù)據(jù)耕腾。


Predicate

斷言、判斷杀糯,對輸入的數(shù)據(jù)根據(jù)某種標準進行評判扫俺,最終返回boolean值:

@FunctionalInterface
public interface Predicate<T> {

    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);

    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * AND of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code false}, then the {@code other}
     * predicate is not evaluated.
     *
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *
     * @param other a predicate that will be logically-ANDed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * AND of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

    /**
     * Returns a predicate that represents the logical negation of this
     * predicate.
     *
     * @return a predicate that represents the logical negation of this
     * predicate
     */
    default Predicate<T> negate() {
        return (t) -> !test(t);
    }

    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * OR of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code true}, then the {@code other}
     * predicate is not evaluated.
     *
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *
     * @param other a predicate that will be logically-ORed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * OR of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    default Predicate<T> or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

    /**
     * Returns a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}.
     *
     * @param <T> the type of arguments to the predicate
     * @param targetRef the object reference with which to compare for equality,
     *               which may be {@code null}
     * @return a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}
     */
    static <T> Predicate<T> isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }
}

Predicate的test 接收T類型的數(shù)據(jù),返回 boolean 類型固翰,即對數(shù)據(jù)進行某種規(guī)則的評判狼纬,如果符合則返回true,否則返回false骂际;Predicate接口還提供了 and疗琉、negate、or歉铝,與 取反 或等没炒,isEqual 判斷兩個參數(shù)是否相等等默認函數(shù)。


Supplier

生產(chǎn)、提供數(shù)據(jù):

@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

非常easy送火,get方法返回一個T類數(shù)據(jù),可以提供重復(fù)的數(shù)據(jù)先匪,或者隨機種子都可以种吸,就這么簡單。

函數(shù)式接口實戰(zhàn)

Consumer

Consumer 用的太多了呀非,不想說太多坚俗,如下:

public class Main {
    public static void main(String[] args) {
      Stream.of(1,2,3,4,5,6)
                .forEach(integer -> System.out.println(integer)); //輸出1,2岸裙,3猖败,4,5降允,6
    }
}

這里使用標準輸出恩闻,還是產(chǎn)生了副作用,但是這種程度是可以允許的


Function

  1. 轉(zhuǎn)換剧董,將字符串轉(zhuǎn)成長度
public class Main {
    public static void main(String[] args) {
       Stream.of("hello","FunctionalInterface")
                .map(e->e.length())
                .forEach(System.out::println);
    }
}

  1. 運算
public class FunctionTest {

    public static void main(String[] args) {

         public static void main(String[] args) {

        Function<Integer, Integer> square = integer -> integer * integer; //定義平方運算

        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);

        list.stream()
                .map(square.andThen(square)) //四次方
                .forEach(System.out::println);

        System.out.println("------");

        list.stream()
                .map(square.compose(e -> e - 1)) //減一再平方
                .forEach(System.out::println);

        System.out.println("------");

        list.stream().map(square.andThen(square.compose(e->e/2))) //先平方然后除2再平方
                .forEach(System.out::println);

    }
}

結(jié)果如圖:

image

Operator

  1. BinaryOperator

這里實現(xiàn)找最大值:

public class BinaryOperatorTest {

    public static void main(String[] args) {

        Stream.of(2,4,5,6,7,1)
                .reduce(BinaryOperator.maxBy(Comparator.comparingInt(Integer::intValue))).ifPresent(System.out::println);

    }
}

Comparator 后期會講到

  1. IntOperator

這里實現(xiàn)累加功能:

public class BinaryOperatorTest {

    public static void main(String[] args) {
        IntBinaryOperator intBinaryOperator = (e1, e2)->e1+e2; //定義求和二元操作
        IntStream.of(2,4,5,6,7,1)
                .reduce(intBinaryOperator).ifPresent(System.out::println);
    }
}


Predicate

篩選出大于0最小的兩個數(shù)

public class Main {

    public static void main(String[] args) {
        IntStream.of(200,45,89,10,-200,78,94)
                .filter(e->e>0) //過濾小于0的數(shù)
                .sorted() //自然順序排序
                .limit(2) //取前兩個
                .forEach(System.out::println);
    }
}


Supplier

這里一直生產(chǎn)2這個數(shù)字幢尚,為了能停下來,使用limit

public class Main {

    public static void main(String[] args) {
        Stream.generate(()->2)
                .limit(10)
                .forEach(System.out::println);
    }
}

如圖:

image

總結(jié)

Java8的Stream 基本上都是使用util.function包下的函數(shù)式接口來實現(xiàn)函數(shù)式編程的翅楼,而函數(shù)式接口也就只分為 Function尉剩、Operator、Consumer毅臊、Predicate理茎、Supplier 這五大類,只要能理解掌握最基礎(chǔ)的五大類用法管嬉,其他變種也能觸類旁通皂林。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市宠蚂,隨后出現(xiàn)的幾起案子式撼,更是在濱河造成了極大的恐慌,老刑警劉巖求厕,帶你破解...
    沈念sama閱讀 222,000評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件著隆,死亡現(xiàn)場離奇詭異,居然都是意外死亡呀癣,警方通過查閱死者的電腦和手機美浦,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,745評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來项栏,“玉大人浦辨,你說我怎么就攤上這事≌由颍” “怎么了流酬?”我有些...
    開封第一講書人閱讀 168,561評論 0 360
  • 文/不壞的土叔 我叫張陵币厕,是天一觀的道長。 經(jīng)常有香客問我芽腾,道長旦装,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,782評論 1 298
  • 正文 為了忘掉前任摊滔,我火速辦了婚禮阴绢,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘艰躺。我一直安慰自己呻袭,他們只是感情好,可當我...
    茶點故事閱讀 68,798評論 6 397
  • 文/花漫 我一把揭開白布腺兴。 她就那樣靜靜地躺著左电,像睡著了一般。 火紅的嫁衣襯著肌膚如雪含长。 梳的紋絲不亂的頭發(fā)上券腔,一...
    開封第一講書人閱讀 52,394評論 1 310
  • 那天,我揣著相機與錄音拘泞,去河邊找鬼纷纫。 笑死,一個胖子當著我的面吹牛陪腌,可吹牛的內(nèi)容都是我干的辱魁。 我是一名探鬼主播,決...
    沈念sama閱讀 40,952評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼诗鸭,長吁一口氣:“原來是場噩夢啊……” “哼染簇!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起强岸,我...
    開封第一講書人閱讀 39,852評論 0 276
  • 序言:老撾萬榮一對情侶失蹤锻弓,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后蝌箍,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體青灼,經(jīng)...
    沈念sama閱讀 46,409評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,483評論 3 341
  • 正文 我和宋清朗相戀三年妓盲,在試婚紗的時候發(fā)現(xiàn)自己被綠了杂拨。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,615評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡悯衬,死狀恐怖弹沽,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤策橘,帶...
    沈念sama閱讀 36,303評論 5 350
  • 正文 年R本政府宣布炸渡,位于F島的核電站,受9級特大地震影響役纹,放射性物質(zhì)發(fā)生泄漏偶摔。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,979評論 3 334
  • 文/蒙蒙 一促脉、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧策州,春花似錦瘸味、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,470評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至孽糖,卻和暖如春枯冈,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背办悟。 一陣腳步聲響...
    開封第一講書人閱讀 33,571評論 1 272
  • 我被黑心中介騙來泰國打工尘奏, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人病蛉。 一個月前我還...
    沈念sama閱讀 49,041評論 3 377
  • 正文 我出身青樓炫加,卻偏偏與公主長得像,于是被迫代替她去往敵國和親铺然。 傳聞我的和親對象是個殘疾皇子俗孝,可洞房花燭夜當晚...
    茶點故事閱讀 45,630評論 2 359

推薦閱讀更多精彩內(nèi)容