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
Well, a
List<IUserPost>
is not anIUserPost
, 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:Or you can use
flatMap
to get aStream<IUserPost>
, which you can then group by user.