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