Given List<Person> persons
, you can have the following
Map<String,List<Person>> map = persons.stream() .flatMap(p -> p.childrenListHolder.children.stream().map(c -> new AbstractMap.SimpleEntry<>(c, p))) .collect(Collectors.groupingBy( e -> e.getKey().childrensName, Collectors.mapping(Map.Entry::getValue, Collectors.toList()) ));
This creates a stream over people. Then each person is densely displayed on the motorcade, holding the child and the person for each child. Finally, we group the name of the child and put all the people on the list.
Sample code assuming appropriate constructors:
public static void main(String[] args) { List<Person> persons = Arrays.asList( new Person("John", new ChildrenListHolder(Arrays.asList(new Children("Lisa"), new Children("Jimmy")))), new Person("Clara", new ChildrenListHolder(Arrays.asList(new Children("Lisa"), new Children("Paul")))), new Person("George", new ChildrenListHolder(Arrays.asList(new Children("Paul")))) ); Map<String,List<Person>> map = persons.stream() .flatMap(p -> p.childrenListHolder.children.stream().map(c -> new AbstractMap.SimpleEntry<>(c, p))) .collect(Collectors.groupingBy( e -> e.getKey().childrensName, Collectors.mapping(Map.Entry::getValue, Collectors.toList()) )); System.out.println(map); }
source share