Java流 - 通过嵌套列表分组(按第二顺序列出)

Bic*_*ick 7 java java-8 java-stream

我有以下数据结构 -

每个学生列表,每个学生都持有一份城市列表.

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;
}
Run Code Online (Sandbox Code Playgroud)

我想得到以下内容.

Map<String, Students> citiesIdsToStudensList;
Run Code Online (Sandbox Code Playgroud)

我写了以下内容

Map<Integer, List<Integer>> statesToStudentsMap = students.stream()
            .flatMap(student -> student.getStates().stream())
            .flatMap(state -> state.getCities().stream())
            .collect(Collectors.groupingBy(City::getId, Collectors.mapping(x -> x.getId(), Collectors.toList())));
Run Code Online (Sandbox Code Playgroud)

但它并没有让我得到我想要的结果.

Tun*_*aki 6

使用Stream API,您需要平面地图两次,并将每个中间学生和城市映射到一个能够抓住学生的元组.

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())
            ));
Run Code Online (Sandbox Code Playgroud)

但是,for在这里使用嵌套循环可能更简洁:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这可以利用computeIfAbsent填充地图并创建具有相同城市ID的每个学生的列表.