Supplier:生产型接口(供给型),内有抽象方法—T get();
没有参数有返回值类型:
@Test
public void test(){
Supplier<String> stringSupplier = () -> {
return "伟大的祖国";
};
String person = stringSupplier.get();
System.out.println(person);
}
UnaryOperator<>函数
一个参数有返回值类型:
@Test
public void test01(){
UnaryOperator<Integer> unaryOperator = (n)->{
return 2*n+1;
};
Integer num = unaryOperator.apply(2);
System.out.println(num);
}
BinaryOperator<>函数
两个参数有返回值类型:
@Test
public void test03(){
BinaryOperator<Integer> binaryOperator = (x,y)->{
return x*y;
};
Integer num = binaryOperator.apply(5,6);
System.out.println(num);
}
Consumer:消费型接口,内有抽象方法—void accept(T t)
一个参数没有返回值类型:
@Test
public void test04(){
Consumer<String> consumer = (name)-> System.out.println(name);
consumer.accept("孙悟空");
}
Function<T, R>:函数型接口,内有抽象方法—R apply(T t)
一个参数一个返回值类型(会比较两个函数给出不同结果):
@Data
@NoArgsConstructor
@AllArgsConstructor
public class EmpVo {
private String account;
private String password;
private String nickname;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Emp {
private String account;
private String password;
private String nickname;
public Emp(String account,String password){
this.account = account;
this.password = password;
}
}
@Test
public void test05(){
Emp[] emps = new Emp[5];
for (int i = 0; i < emps.length; i++) {
emps[i] = new Emp("emp"+(i+1),"123456","emp"+(i+1));
}
Emp login = new Emp("emp2","123456");
Function<Emp, EmpVo> function = (emp)->{
for (Emp db:emps
) {
if(db.getAccount().equals(emp.getAccount()) && db.getPassword().equals(emp.getPassword())){
return new EmpVo(db.getAccount(), db.getPassword(), db.getNickname());
}
}
return null;
};
EmpVo empVo = function.apply(login);
if (empVo == null) {
System.out.println("账号或密码错误");
}else{
System.out.println("员工"+ empVo.getNickname()+"登录");
}
}
Predicate:断言型接口,内有抽象方法—boolean test(T t)
@Test
public void test08() {
Emp[] emps = new Emp[5];
for (int i = 0; i < emps.length; i++) {
emps[i] = new Emp("emp" + (i + 1), "123456", "emp" + (i + 1));
}
Emp login = new Emp("emp2", "123456");
Predicate<Emp> predicate = (emp) -> {
for (Emp db : emps
) {
if (db.getAccount().equals(emp.getAccount()) && db.getPassword().equals(emp.getPassword())) {
return true;
}
}
return false;
};
boolean test = predicate.test(login);
if (test) {
System.out.println("登陆成功");
} else {
System.out.println("登陆失败");
}
}