英文:
Java 8 groupingBy: Simple Grouping by a Single Column
问题
我想使用Java 8中的groupingBy收集器按单个列进行简单分组,所以我做了以下操作:
Map<IUser, List<IUserPost>> postsPerUser =
autorisationUsersRepository.findById(dateReference)
.stream()
.map(UsersMapper::map)
.flatMap(user -> user.getPosts().stream())
.collect(Collectors.groupingBy(IUserPost::getUser));
但是我遇到了这个编译错误:
所需类型:
Collector<? super List<IUserPost>, A, R>
已提供类型:
Collector<IUserPost, capture of ?, Map<IUser, List<IUserPost>>>
原因:不存在类型变量的实例,使得List<IUserPost>符合IUserPost
英文:
I want to do simple Grouping by a Single Column using Java 8 groupingBy Collector, so I did this:
Map<IUser, List<IUserPost>> postsPerUser =
autorisationUsersRepository.findById(dateReference)
.stream()
.map(UsersMapper::map) -> Stream<IUser>
.map(IUser::getPosts) -> Stream<List<IUserPost>>
.collect(groupingBy(IUserPost::getUser));
but I have this compilation error:
Required type:
Collector
<? super List<IUserPost>,
A,
R>
Provided:
Collector
<IUserPost,
capture of ?,
Map<IUser, List<IUserPost>>>
reason: no instance(s) of type variable(s) exist so that List<IUserPost> conforms to IUserPost
答案1
得分: 1
好的,以下是您要求的翻译内容:
好吧,List<IUserPost>
不是 IUserPost
,所以你可以以那种方式对它们进行分组。
你可以直接使用Collectors.toMap()
收集到一个映射中,将键(用户)映射为自身,将值映射为其帖子的列表:
postsPerUser =
autorisationUsersRepository.findById(dateReference).stream()
.map(UsersMapper::map) // Stream<IUser>
.collect(toMap(user -> user, IUser::getPosts)) // Map<IUser, List<IUserPost>>
或者你可以使用flatMap
获得一个Stream<IUserPost>
,然后可以按用户进行分组。
postsPerUser =
autorisationUsersRepository.findById(dateReference).stream()
.map(UsersMapper::map) // Stream<IUser>
.flatMap(IUser::getPosts) // Stream<IUserPost>
.collect(groupingBy(IUserPost::getUser)) // Map<IUser, List<IUserPost>>
英文:
Well, a List<IUserPost>
is not an IUserPost
, so you can group those in that way.
You can collect directly to a map using Collectors.toMap()
, mapping the key (user) to itself and the value to the list of their posts:
postsPerUser =
autorisationUsersRepository.findById(dateReference).stream()
.map(UsersMapper::map) // Stream<IUser>
.collect(toMap(user -> user, IUser::getPosts)) // Map<IUser, List<IUserPost>>
Or you can use flatMap
to get a Stream<IUserPost>
, which you can then group by user.
postsPerUser =
autorisationUsersRepository.findById(dateReference).stream()
.map(UsersMapper::map) // Stream<IUser>
.flatMap(IUser::getPosts) // Stream<IUserPost>
.collect(groupingBy(IUserPost::getUser)) // Map<IUser, List<IUserPost>>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论