Man*_* Zi 2 java lambda dictionary java-8 collectors
如果我们成像,我们有一个名为person的对象,而人看起来像下面这样:
class Person {
int id;
String name;
String country
// ...
// getter/setter
}
Run Code Online (Sandbox Code Playgroud)
我们有一个List
的Person
对象,我们要"转换"到一个地图.我们可以使用以下内容:
Map<Long, List<Person>> collect = personList.stream().
collect(Collectors.toMap(Person::getId, p -> p));
Run Code Online (Sandbox Code Playgroud)
但是可以返回valuemapper的默认值并更改valuemapper的类型?
我想过这样的事情:
Map<Long, List<Person>> collect =
personList.stream().collect(Collectors.groupingBy(Person::getId, 0));
Run Code Online (Sandbox Code Playgroud)
但有了这个我得到以下错误 is not applicable for the arguments
我有一个解决方法,但我认为它不是很漂亮.
Map<Long, Object> collect2 = personList.stream().
collect(Collectors.toMap(Person::getId, pe -> {
return 0;
}));
Run Code Online (Sandbox Code Playgroud)