Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading