java8 方法中 传递函数

目的:

    想向Scala的面向函数一样,在Java中也进行函数当做参数的传递。


流程:

    首先需要定义一个函数接口:

  1. @FunctionalInterface
  2. public interface FilterPhoneFuction {
  3. boolean filter(String phone);
  4. default String getInfo(){
  5. return "过滤手机号函数" ;
  6. }
  7. }

    请注意java8中对函数接口定义的规范原则。


其次实现该接口:

  1. public static void main(String[] args) {
  2. FilterPhoneFuction phoneFuction = (phone)->{
  3. System.out.println(phone);
  4. return true ;
  5. };
  6. // phoneFuction.filter("aa");
  7. hancle(phoneFuction);
  8. }



然后看看是如何调用的:

  1. private static void hancle(FilterPhoneFuction phoneFuction) {
  2. List<String> list = Lists.newArrayList() ;
  3. list.add("aa");
  4. list.add("bb");
  5. list.add("cc") ;
  6. list.stream().forEach(phoneFuction::filter);
  7. // List<String> phoneList = readTxtFile("");//获取手机号
  8. }

打印:

aa
bb
cc


总结:如此来看Java也是可以进行函数的传递的,这样提供面向函数会方便很多。