您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在 Java 中,方法引用(Method Reference)是一种简化 Lambda 表达式的写法。它允许你引用已经存在的方法或构造函数。方法引用主要有四种类型:
下面是如何使用方法引用的示例:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public class MethodReferenceExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
// 静态方法引用
List<String> lowerCaseNames = names.stream()
.map(String::toLowerCase)
.collect(Collectors.toList());
System.out.println(lowerCaseNames); // 输出: [alice, bob, charlie]
// 特定对象的实例方法引用
Person person = new Person("John");
List<String> namesWithInitials = names.stream()
.map(name -> person.getName().concat(". ").concat(name))
.collect(Collectors.toList());
System.out.println(namesWithInitials); // 输出: [John. Alice, John. Bob, John. Charlie]
// 任意对象的实例方法引用
List<Integer> lengths = names.stream()
.map(String::length)
.collect(Collectors.toList());
System.out.println(lengths); // 输出: [5, 3, 6]
// 构造方法引用
List<Person> people = names.stream()
.map(Person::new)
.collect(Collectors.toList());
System.out.println(people); // 输出: [Person{name='Alice'}, Person{name='Bob'}, Person{name='Charlie'}]
}
}
在这个示例中,我们使用了不同的方法引用来处理一个字符串列表。这些方法引用分别引用了 String
类的静态方法 toLowerCase()
、Person
类的实例方法 getName()
、任意对象的实例方法 length()
以及 Person
类的构造方法。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。