/**
* 方法引用的使用要求: 要求接口中的抽象方法的形参列表和返回值类型与方法引用的方法的形参列表和返回值类型相同
*/
@Test
public void test6() {
// 1. 对象::实例方法(非静态方法)
//传一个参数,不返回值
Consumer<String> consumer = x -> System.out.println(x);
consumer.accept("demo");
Consumer<String> consumer1 = System.out::println;
consumer.accept("demo1");
//不传参数,返回值
Supplier<People> peopleSupplier = People::new;
System.out.println(peopleSupplier.get());
// 2. 类::静态方法
//传两个参数,返回一个值
Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y);
System.out.println(comparator.compare(1, 2));
Comparator<Integer> comparator1 = Integer::compare;
System.out.println(comparator1.compare(2, 1));
// 传一个类型的参数,返回另一个类型的值
Function<Double, Long> function = (x) -> Math.round(x);
System.out.println(function.apply(12.3));
Function<Double, Long> function1 = Math::round;
System.out.println(function1.apply(12.6));
//3. 类::非静态方法
Comparator<String> comparator2 = (x,y)-> x.compareTo(y);
System.out.println(comparator2.compare("a","b"));
Comparator<String> comparator3 = String::compareTo;
System.out.println(comparator3.compare("a", "a"));
People people1 = new People();
Function<People,String> function2 = people -> people.getName();
System.out.println(function2.apply(people1));
Function<People,String> function3 = People::getName;
System.out.println(function3.apply(people1));
}
}
class People {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
String name;
@Override
public String toString() {
return "People{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
public People() {
this.name = "name";
this.sex = "female";
this.age = 18;
}
String sex;
int age;
}