首页 > 基础资料 博客日记
Java8 方法引用
2023-07-29 17:40:26基础资料围观234次
Java资料网推荐Java8 方法引用这篇文章给大家,欢迎收藏Java资料网享受知识的乐趣
/**
* 方法引用的使用要求: 要求接口中的抽象方法的形参列表和返回值类型与方法引用的方法的形参列表和返回值类型相同
*/
@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;
}
文章来源:https://www.cnblogs.com/yan061/p/16506243.html
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
标签: