User::getName — 方法引用
介绍
List<String>names=users.stream().map(User::getName)// Function<User, String>.collect(Collectors.toList());里User::getName是什么意思意思很明白返回
但User::getName 为什么这样写?
User::getName 是 Java 8 引入的方法引用语法,它是 Lambda 表达式的简写形式。
等价于
(Useruser)->user.getName()因为 Stream.map() 需要一个 Function<User, String> 类型的参数:
<R>Stream<R>map(Function<?superT,?extendsR>mapper)所以编译器会自动把 User::getName 转换成对应的 Function
List<User>users=...;// 写法一:方法引用(最简洁)List<String>names1=users.stream().map(User::getName).collect(Collectors.toList());// 写法二:Lambda 表达式List<String>names2=users.stream().map(user->user.getName()).collect(Collectors.toList());// 写法三:匿名内部类(最啰嗦)List<String>names3=users.stream().map(newFunction<User,String>(){@OverridepublicStringapply(Useruser){returnuser.getName();}}).collect(Collectors.toList());三种写法效果完全一样,推荐用写法一(方法引用)
方法引用的四种形式
| 形式 | 语法 | 示例 | 等价 Lambda |
|---|---|---|---|
| 静态方法引用 | 类名::静态方法 | Integer::parseInt | s -> Integer.parseInt(s) |
| 实例方法引用 | 对象::实例方法 | str::length | () -> str.length() |
| 任意对象的实例方法 | 类名::实例方法 | String::length | str -> str.length() |
| 构造方法引用 | 类名::new | User::new | () -> new User() |
其他例子
// 静态方法引用List<String>strList=Arrays.asList("1","2","3");List<Integer>intList=strList.stream().map(Integer::parseInt)// 等价于 s -> Integer.parseInt(s).collect(Collectors.toList());// 构造方法引用List<User>users=names.stream().map(User::new)// 等价于 name -> new User(name).collect(Collectors.toList());// 任意对象的实例方法List<String>words=Arrays.asList("hello","world");List<Integer>lengths=words.stream().map(String::length)// 等价于 s -> s.length().collect(Collectors.toList());User::getName 就是 “调用每个 User 对象的 getName() 方法” 的简写,本质是一个 Function<User, String>。它是 Java 8 方法引用语法,比 Lambda 更简洁、可读性更强。
