java8-Function的使用


https://blog.csdn.net/huo065000/article/details/78964382

因為function是一個接口,所以如果在類中使用的話直接定義function使用應該也可以,類似這樣:

Function<String, Integer> getStringLength = t -> t.length();

然后將這個函數對象進行調用(感覺跟scala的用法差不多,scala里函數是第一公民 ,現在 java也搞了函數式編程)

個人測試:

Function的簡單使用:

  @Test
    public void method1() {
        Function<Integer, Integer> fun1 = n->n*2 ;
        Function<Integer, Integer> fun2 = n->n*n ;
        //andThen  先用自己,然后then再用其它
        System.out.println(fun1.andThen(fun2).apply(3));//36
        //compose 先調用其它在用自己
        System.out.println(fun1.compose(fun2).apply(3));//18
    }

biFunction的簡單使用:

 /**
     *biFunction的使用
     */
    @Test
    public void method2() {
        BiFunction<String,String,Integer> biFun=(s1,s2)->s1.length()+s2.length();
        System.out.println(biFun.apply("abc","d"));//4
    }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM