Java学习笔记

JDK 8 -- Function接口: apply, comp

2017-01-10  本文已影响328人  ted005

1 Function<T, R>中的T, R表示接口输入、输出的数据类型。

2 BiFunction<T, U, R>中的T, U表示接口输入的第一、第二个参数、R是输出的数据类型。

 public class BIFunctionTest {    
       public static void main(String[] args) {        
              //定义BiFunction对象,并调用apply方法
              BiFunction<Integer, String, Integer> biFunction = (t, u) -> {
                                         return t + Integer.parseInt(u);
                                    };   
              System.out.println(biFunction.apply(5, "6")); //11   
              
              System.out.println("------------------------------------------");        
              
              //方法调用时,作为参数(操作)传入        
              BIFunctionTest biFunctionTest = new BIFunctionTest();      
              int result = biFunctionTest.compute(5, 6, (t, u) -> {return t + u;});        
              System.out.println(result); //11        
              
              //BiFunction与Function的组合       
              int result2 = biFunctionTest.compute2(5, 6, (t, u) -> {return t + u;}, t -> t * t);        
              System.out.println(result2); //121    
       }    

       public int compute(Integer a, Integer b, BiFunction<Integer, Integer, Integer> biFunction) {
              return biFunction.apply(a, b);    
       }    

       //BIFunction的返回作为Function的输入    
       public int compute2(Integer a, Integer b, BiFunction<Integer, Integer, Integer> biFunction, Function<Integer, Integer> function) {       
             return biFunction.andThen(function).apply(a, b);   
       }}
上一篇 下一篇

猜你喜欢

热点阅读