当前位置: 代码迷 >> 综合 >> Java8 新特性之四大核心函数式接口
  详细解决方案

Java8 新特性之四大核心函数式接口

热度:68   发布时间:2023-12-27 01:22:14.0

目录

消费型接口:只接收一个参数,没有返回值

供给型接口:无需参数,返回一个泛型的结果

函数型接口:需要指定两个泛型 ,第一个泛型作为apply 的参数,apply 返回的是第二个泛型的结果

断言型接口:接收一个参数,返回 boolean 类型的结果


Consumer<T>: 消费型接口void accept(T t);Supplier<T>: 供给型接口T get();Function<T, R>: 函数型接口R apply(T t);Predicate<T>: 断言型接口boolean test(T t);

消费型接口:只接收一个参数,没有返回值

Consumer<T>: 消费型接口void accept(T t);
@Test
public void consumer(){happy(1000, (x)-> System.out.println("happy 消费: "+ x + " 元"));
}public void happy(double money, Consumer<Double> con){con.accept(money);
}

供给型接口:无需参数,返回一个泛型的结果

Supplier<T>: 供给型接口T get();
@Test
public void supplier(){List<Integer> list = getNumList(10, () -> (int) (Math.random() * 10));for (Integer integer : list) {System.out.print(integer + " ");}
}// 返回 num 个随机数,随机数以 List 形式返回
public List<Integer> getNumList(int num, Supplier<Integer> sup){List<Integer> list = new ArrayList<>();for (int i = 0; i < num; i++) {Integer value = sup.get();list.add(value);}return list;
}

函数型接口:需要指定两个泛型 ,第一个泛型作为apply 的参数,apply 返回的是第二个泛型的结果

Function<T, R>: 函数型接口R apply(T t);
@Test
public void function() {String res = trimFunction("\t\t\t trim function", (str) -> str.trim());System.out.println(res);
}public String trimFunction(String str, Function<String, String> func) {return func.apply(str);
}

断言型接口:接收一个参数,返回 boolean 类型的结果

Predicate<T>: 断言型接口boolean test(T t);
@Test
public void predicated(){List<String> list = Arrays.asList("java", "c++", "python", "c#", "javascript");// 提取出含有字符串 "c" 的字符串List<String> ans = filterString(list, (str) -> str.contains("c"));for (String item : ans) {System.out.print(item + " ");}
}public List<String> filterString(List<String> list, Predicate<String> pre){List<String> res = new ArrayList<>();for (String str : list) {if (pre.test(str)) {res.add(str);}}return res;
}