目录
函数型接口:需要指定两个泛型 ,第一个泛型作为apply 的参数,apply 返回的是第二个泛型的结果
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;
}