消费型函数式接口 Consumer<T> 常用于遍历 void accpet(T t) 供给型函数式接口 Supplier<T> 用于产生数据 T get() 断言型函数式接口 Predicate<T> 用于判断 boolean test(T t) 函数型函数式接口 Function<T,R> 用于逻辑处理 R apply(T t) @FunctionalInterface 注解用于判断一个接口是不是函数式接口 public class LambdaTest { public static void main(String[] args) { /* 消费式函数式接口测试 happy(100.23,(m)-> System.out.println("消费了"+m));*/ /* 供给型函数式接口测试 List<Integer> numIntegers = getNumIntegers(2, () -> (int) (Math.random() * 100)); System.out.println(numIntegers);*/ /* 函数型函数式接口测试 String s1 = dealString(" hel lo nice ", (s) -> s.toUpperCase().trim().replace(" ","")); System.out.println(s1);*/ /* 断言型函数式接口测试 Integer[] integers={1,3,4,7,5,8,6,2}; List<Integer> list = selectBig5(integers, (m) -> m > 5); System.out.println(list);*/ } //消费型函数式接口 Consumer<T> : void accept(T t) public static void happy(Double money, Consumer consumer){ consumer.accept(money); } //供给型函数式接口 Supplicer<T> int get() public static List<Integer> getNumIntegers(Integer num, Supplier<Integer> supplier){ ArrayList<Integer> integers = new ArrayList<>(); for (Integer i = 0; i < num; i++) { Integer integer = supplier.get(); integers.add(integer); } return integers; } //函数型函数式接口 Function<T,R> R apply(T t) public static String dealString(String string, Function<String,String> function){ return function.apply(string); } //断言型函数式接口 Predicate<T> boolean test(T t) public static List<Integer> selectBig5(Integer[] integers, Predicate<Integer> predicate){ List<Integer> list =new ArrayList<>(); for (Integer integer : integers) { if (predicate.test(integer)){ list.add(integer); } } return list; } }
四种常见函数式接口
最新推荐文章于 2023-12-28 21:20:08 发布