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
    }

  

posted @ 2018-08-22 11:24  forward22222  阅读(2430)  评论(0)    收藏  举报