This question already has an answer here:
这个问题在这里已有答案:
- how to use java 8 stream and lambda to flatMap a groupingBy result 2 answers
如何使用java 8 stream和lambda来flatMap一个groupingBy结果2个答案
I have a person
我有一个人
class Person{
private Long id;
private String firstName;
private String lastName;
//with getters and setters
}
I have a following method that receives a person's id and returns a list of tags that are associated with the person
我有一个以下方法接收一个人的id并返回与该人相关联的标签列表
public List<String> getTags(Long personId){
/*ExampleImplementation*/
someCollection.stream()
.filter(Objects::nonNull)
.map(SomeType::someMethod)
.filter(Objects:nonNull)
.collect(Collectors.toList());
}
I am building a method in order to get a map of all the personIds and the list of tags associated with the personId.
我正在构建一个方法,以获取所有personIds的映射以及与personId关联的标记列表。
public Map<Long, List<String>>getPersonTags(List<Long> personIds){
return personIds.stream()
.collect(Collectors.groupingBy(
(personId) -> personId,
Collectors.mapping(this::getTags, Collectors.toList())));
}
But getPersonTags()
is returning a Map<Long, List<List<String>>>
but I expect a Map<Long, List<String>>
What should I change to get my expected return type.
但getPersonTags()返回一个Map
1 个解决方案
#1
1
If personIds
contains distinct values, you don't need to use groupingBy()
. Use toMap()
instead:
如果personIds包含不同的值,则不需要使用groupingBy()。使用toMap()代替:
return personIds.stream()
.collect(Collectors.toMap(Function.identity(), this::getTags));
#1
1
If personIds
contains distinct values, you don't need to use groupingBy()
. Use toMap()
instead:
如果personIds包含不同的值,则不需要使用groupingBy()。使用toMap()代替:
return personIds.stream()
.collect(Collectors.toMap(Function.identity(), this::getTags));