函数式编程

193 阅读1分钟

函数式编程

小白普及

进阶

常用函数式接口

  • Consumer 消费型接口
  Consumer consumer = System.out::println;
  consumer.accept("hello function");
  • Supplier 供给型接口
 Supplier<String> supplier = () -> "我要变的很有钱";
 System.out.println(supplier.get());
  • Function<T,R> 函数型接口
 Function<Integer, Integer> function1 = e -> e * 6;
 System.out.println(function1.apply(2));
  • Predicate 断言型接口
 Predicate<Integer> predicate = t -> t > 0;
 boolean test = predicate.test(1);
 System.out.println(test);

进阶使用

  • Predicate 的使用:
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
 
public class Java8Tester {
   public static void main(String args[]){
      List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        
      // Predicate<Integer> predicate = n -> true
      // n 是一个参数传递到 Predicate 接口的 test 方法
      // n 如果存在则 test 方法返回 true
        
      System.out.println("输出所有数据:");
        
      // 传递参数 n
      eval(list, n->true);
        
      // Predicate<Integer> predicate1 = n -> n%2 == 0
      // n 是一个参数传递到 Predicate 接口的 test 方法
      // 如果 n%2 为 0 test 方法返回 true
        
      System.out.println("输出所有偶数:");
      eval(list, n-> n%2 == 0 );
        
      // Predicate<Integer> predicate2 = n -> n > 3
      // n 是一个参数传递到 Predicate 接口的 test 方法
      // 如果 n 大于 3 test 方法返回 true
        
      System.out.println("输出大于 3 的所有数字:");
      eval(list, n-> n > 3 );
   }
    
   public static void eval(List<Integer> list, Predicate<Integer> predicate) {
      for(Integer n: list) {
        
         if(predicate.test(n)) {
            System.out.println(n + " ");
         }
      }
   }
}
  • 计算demo

函数式编程-统计功能(使用对象的getter方法和过滤条件作为参数)