Nuñito Calzada
Nuñito Calzada

Reputation: 2056

Java 8 groupingBy: Simple Grouping by a Single Column

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

Upvotes: 0

Views: 633

Answers (1)

Polygnome
Polygnome

Reputation: 7795

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>>

Upvotes: 1

Related Questions