Skip to content

Instantly share code, notes, and snippets.

@javagrails
Last active January 11, 2019 06:52
Show Gist options
  • Save javagrails/896333f2dedea9e2fa31567b9381ec26 to your computer and use it in GitHub Desktop.
Save javagrails/896333f2dedea9e2fa31567b9381ec26 to your computer and use it in GitHub Desktop.
java stream nested groupingBy

Scenerio

public class Student {
private int id;
private String name;
private List<State> states = new ArrayList<>();
}

public class State {
    private int id;
    private String name;
    private List<City> Cities = new ArrayList<>();
}

public class City {
    private int id;
    private String name;
}

Possibple Solutions

  Map<Integer, List<Student>> citiesIdsToStudentsList =
    students.stream()
            .flatMap(student -> student.getStates().stream().map(state -> new AbstractMap.SimpleEntry<>(student, state)))
            .flatMap(entry -> entry.getValue().getCities().stream().map(city -> new AbstractMap.SimpleEntry<>(entry.getKey(), city)))
            .collect(Collectors.groupingBy(
                entry -> entry.getValue().getId(),
                Collectors.mapping(Map.Entry::getKey, Collectors.toList())
            ));

  Map<Integer, List<Student>> citiesIdsToStudentsList = new HashMap<>();
for (Student student : students) {
    for (State state : student.getStates()) {
        for (City city : state.getCities()) {
            citiesIdsToStudentsList.computeIfAbsent(city.getId(), k -> new ArrayList<>()).add(student);
        }
    }
}

  Map<Integer, List<Student>> citiesIdsToStudentsList =
    students.stream()
        .flatMap(student -> student.getStates().stream()
            .flatMap(state -> state.getCities().stream())
            .map(state -> new AbstractMap.SimpleEntry<>(student, state.getId())))
        .collect(Collectors.groupingBy(
            Map.Entry::getValue,
            Collectors.mapping(Map.Entry::getKey, Collectors.toList())
        ));

Sorce : https://stackoverflow.com/questions/36960226/java-stream-groupingby-by-a-nested-list-list-in-a-second-order

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment