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