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 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());
      }
  }

Thank you

  • 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())))));` – Hadi J Aug 12 '21 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()); }` – Holger Aug 12 '21 at 16:00

1 Answers1

1

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.

udalmik
  • 7,838
  • 26
  • 40
  • 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())))));` – Hadi J Aug 12 '21 at 15:30
  • 2
    I’d rather use the `flatMapping` implementation shown at the end of [this answer](https://stackoverflow.com/a/39131049/2711488) in Java 8. – Holger Aug 12 '21 at 16:13
  • Thx, looks good, I added ref to this answer as well – udalmik Aug 13 '21 at 08:11