0

I have a AssistantList and need to map to Map of (Key - Assistant Login, Value - ArrayList of its Supervisor)

I used below code to map using for loop.

How can I use the Stream API to achieve the same functionality?

for(Assistant assistant: assistantList)
{
    for(Supervisor supervisor: assistant.getSupervisorList())
    {
            map.computeIfAbsent(assistant.getLogin(), 
                    k->new ArrayList<>()).add(supervisor.getLogin());
    }
}
2
  • I think current way is more readable. BTW java stream version like this: assistantList.stream() .collect(groupingBy(Assistant::getLogin, Collectors.mapping(Assistant::getSupervisorList, Collectors.collectingAndThen(Collectors.toList(), lists -> lists.stream().flatMap(List::stream).map(Supervisor::getLogin).collect(Collectors.toList()))))); Commented Aug 12, 2021 at 15:29
  • 2
    I’d rather use for(Assistant assistant: assistantList) { List<…> l = map.computeIfAbsent(assistant.getLogin(), k->new ArrayList<>()); for(Supervisor supervisor: assistant.getSupervisorList()) l.add(supervisor.getLogin()); } Commented Aug 12, 2021 at 16:00

1 Answer 1

2

I think you can use combination of groupBy for grouping and flatMapping for merging the supervisors:

import static java.util.stream.Collectors.flatMapping;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;

Map<String, List<String>> grouped = assistantList.stream()
        .collect(groupingBy(
                Assistant::getLogin,
                flatMapping(
                        assistant -> assistant.getSupervisorList()
                                .stream()
                                .map(Supervisor::getLogin),
                        toList())
        ));
    }
}

Also I think Map<String, Set<String>> could work better, to remove possible supervisor duplicate values.

flatMapping is Java 9+ collector, for Java 8 you can check this and this answers on possible alternatives.

Sign up to request clarification or add additional context in comments.

3 Comments

java 8 version like this: assistantList.stream() .collect(groupingBy(Assistant::getLogin, Collectors.mapping(Assistant::getSupervisorList, Collectors.collectingAndThen(Collectors.toList(), lists -> lists.stream().flatMap(List::stream).map(Supervisor::getLogin).collect(Collectors.toList())))));
I’d rather use the flatMapping implementation shown at the end of this answer in Java 8.
Thx, looks good, I added ref to this answer as well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.