包括:
一. Function 接口的使用
二. Consumer 接口的使用 和 Function 接口的区别
三. Predicate 接口的使用
R apply(T t);
public class Test {
public static void main(String[] args) throws InterruptedException {
String name = "";
String name1 = "12345";
System.out.println(validInput(name, inputStr -> inputStr.isEmpty() ? "名字不能为空":inputStr));
System.out.println(validInput(name1, inputStr -> inputStr.length() > 3 ? "名字过长":inputStr));
}
public static String validInput(String name,Function function) {
return function.apply(name);
}
}
void accept(T t);
public class Test {
public static void main(String[] args) throws InterruptedException {
String name = "";
String name1 = "12345";
validInput(name, inputStr ->
System.out.println(inputStr.isEmpty() ? "名字不能为空":"名字正常"));
validInput(name1, inputStr ->
System.out.println(inputStr.isEmpty() ? "名字不能为空":"名字正常"));
}
public static void validInput(String name,Consumer function) {
function.accept(name);
}
}
validInput(name1, inputStr -> inputStr.length() > 3 ?
System.out.println("名字过长"):System.out.println("名字正常"));
错误显示为:
The method validInput(String, Consumer) in the type Test is not applicable for the arguments (String, ( inputStr) -> {})
boolean test(T t);
Demo,还是如上面的例子:
public class Test {
public static void main(String[] args) throws InterruptedException {
String name = "";
String name1 = "12";
String name2 = "12345";
System.out.println(validInput(name,inputStr -> !inputStr.isEmpty() && inputStr.length() <= 3 ));
System.out.println(validInput(name1,inputStr -> !inputStr.isEmpty() && inputStr.length() <= 3 ));
System.out.println(validInput(name2,inputStr -> !inputStr.isEmpty() && inputStr.length() <= 3 ));
}
public static boolean validInput(String name,Predicate function) {
return function.test(name);
}
}
输出为:
false
true
false