Jmi*_*ini 3 java generics java-stream collectors
鉴于这个简单的人POJO:
public class Person {
private String id;
private String name;
public Person(String id, String name) {
super();
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
}
Run Code Online (Sandbox Code Playgroud)
我想收集Map<String, Person>钥匙是id人的钥匙.
我试图像这样实现它:
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class CollectorMain {
public static void main(String[] args) {
List<Person> list = new ArrayList<>();
list.add(new Person("312", "John"));
list.add(new Person("454", "Alice"));
list.add(new Person("712", "Bob"));
Map<String, Person> map = list.stream()
.collect(
Collectors.toMap(Person::getId, Function::identity) // COMPILE ERROR
);
System.out.println(map.size());
}
}
Run Code Online (Sandbox Code Playgroud)
但我得到一个编译错误:
CollectorMain.java:[14,41] no suitable method found for toMap(Person::getId,Function::identity)
method java.util.stream.Collectors.<T,K,U>toMap(java.util.function.Function<? super T,? extends K>,java.util.function.Function<? super T,? extends U>) is not applicable
(cannot infer type-variable(s) T,K,U
(argument mismatch; incompatible parameter types in method reference))
method java.util.stream.Collectors.<T,K,U>toMap(java.util.function.Function<? super T,? extends K>,java.util.function.Function<? super T,? extends U>,java.util.function.BinaryOperator<U>) is not applicable
(cannot infer type-variable(s) T,K,U
(actual and formal argument lists differ in length))
method java.util.stream.Collectors.<T,K,U,M>toMap(java.util.function.Function<? super T,? extends K>,java.util.function.Function<? super T,? extends U>,java.util.function.BinaryOperator<U>,java.util.function.Supplier<M>) is not applicable
(cannot infer type-variable(s) T,K,U,M
(actual and formal argument lists differ in length))
Run Code Online (Sandbox Code Playgroud)
作为一个解决方案,我可以像这样替换Function::identity这个lambda p -> p:
Map<String, Person> map = list.stream()
.collect(
Collectors.toMap(Person::getId, p -> p)
);
Run Code Online (Sandbox Code Playgroud)
有可能使用Function::identity吗?
您不应该使用方法参考.你应该用Function.identity().
如果你使用方法参考,你基本上试图传递一个Supplier<Function<T, T>>.
Map<String, Person> map = list.stream().collect(
Collectors.toMap(Person::getId, Function.identity())
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1973 次 |
| 最近记录: |