How to add keys and values to Collectors.toMap() by going through the list?

101 Views Asked by At
    Map<String,List<MeetupDTO>> employeesMeetups = new HashMap<>(employeesId.size());
    for(String  employeeId : employeesId) {
        List<MeetupDTO> meetups = meetupRepository.
                getAllByEmployeeId(employeeId).
                stream().
                map(meetupMapper::toDTO).
                collect(Collectors.toList());
        employeesMeetups.put(employeeId,meetups);
    return employeesMeetups;

I want to change what's on top to the bottom.

    return Collectors.toMap(//How do I add keys here?,
            employeesId.
            stream().
            forEach(e->meetupRepository.getAllByEmployeeId(e).
                    stream().
                    map(meetupMapper::toDTO).
                    collect(Collectors.toList())
            ));

I don't know how to make the keys match their list, how can this be implemented?

2

There are 2 best solutions below

4
Diego Borba On BEST ANSWER

You can use Collectors.toMap(), this way:

Map<String, List<MeetupDTO>> employeesMeetups = employeesId.stream()
    .collect(Collectors.toMap(
        employeeId -> employeeId, // Key mapper
        employeeId -> meetupRepository.getAllByEmployeeId(employeeId).stream()
            .map(meetupMapper::toDTO)
            .collect(Collectors.toList()) // Value mapper
    ));

Important: while using the toMap() collector, you need to ensure that the keys are unique, or else you might encounter an IllegalStateException.

Edit

The key is a unique user id, do I need to look at whether the key is unique in this case? - Будь как Я

@DiegoBorba you can use employeesId.distinct().stream().collect.. to be safe in case it does have duplicates - 01000001

Using unique IDs, stream() is enough, but in cases where values can repeat, you can use distinct(), as 01000001 said.

3
Oleg Cherednik On

Why not use simple loop?

public static Map<String, List<MeetupDTO>> getEmployeeMetups(
                                                     Set<String> employeeIds) {
    Map<String, List<MeetupDTO>> map = new HashMap<>();

    for (String employeeId : employeeIds) {
        List<MeetupDTO> dtos =
                   meetupRepository.getAllByEmployeeId(employeeId).stream()
                                   .map(meetupMapper::toDTO)
                                   .collect(Collector.toList());

        map.put(employeeId, dtos);
    }

    return map;
}