Search code examples
javajava-streamcollectors

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


    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?


Solution

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