这里写自定义目录标题
1. Java内置的四大核心函数式接口
-
Consumer 消费型接口 消费对象
void accept(T t);
public class Test {
public static void helloWorld(String str, Consumer<String> consumer){
consumer.accept(str);
}
public static void main(String[] args) {
helloWorld("HelloWorld", (x)-> System.out.println(x));
}
}
- Supplier 供给型接口 生成对象
T get();
public class Test {
public static void helloWorld(Supplier<Integer> supplier){
System.out.println(supplier.get());
}
public static void main(String[] args) {
helloWorld(() ->666);
}
}
- Function<R,T> 函数型接口 指定特定功能
R apply(T t);
public class Test {
public static Integer helloWorld(Integer i, Function<Integer, Integer> function){
return function.apply(i);
}
public static void main(String[] args) {
Integer j = helloWorld(20,(x) ->{
Integer in = 0;
for (int i = 0; i < x; i++) {
in++;
}
return in;
});
System.out.println(j);
}
}
- Predicate 断言型接口 进行条件判断
boolean test(T t);
public class Test {
public static Boolean helloWorld(List<String> strs, Predicate<String> predicate){
for (String str : strs) {
if (predicate.test(str)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
List<String> strs = new ArrayList<>();
strs.add("A");
strs.add("B");
strs.add("C");
strs.add("D");
strs.add("E");
Boolean b = helloWorld(strs, (x) -> x.length() > 2);
System.out.println(b);
}
}