我对该Function.identity()方法的用法有疑问.
想象一下以下代码:
Arrays.asList("a", "b", "c")
.stream()
.map(Function.identity()) // <- This,
.map(str -> str) // <- is the same as this.
.collect(Collectors.toMap(
Function.identity(), // <-- And this,
str -> str)); // <-- is the same as this.
Run Code Online (Sandbox Code Playgroud)
是否有任何理由你应该使用Function.identity()而不是str->str(反之亦然).我认为第二种选择更具可读性(当然是品味问题).但是,有没有"真正的"理由为什么应该首选?
我们Map在对象列表中使用几个简单的内存DB:
class Person {
public String id;
public String phone;
public String email;
// and get/set and other fields...
}
List<Person> persons;
Map<String, Person> emailLookup = persons.stream()
.collect(Collectors.toMap(Person::getEmail, p -> p));
Map<String, Person> phoneLookup = persons.stream()
.collect(Collectors.toMap(Person::getPhone, p -> p));
Map<String, Person> idLookup = persons.stream()
.collect(Collectors.toMap(Person::getId, p -> p));
Run Code Online (Sandbox Code Playgroud)
在Java SE中是否有任何语法糖或内置函数替换 p -> p为其他东西?