我有以下数据结构-
Students 列表,每个 Students 都有一个 States 列表,每个州都有一个城市列表。
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<String, Students> citiesIdsToStudensList;
我写了以下内容
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())));
但它并没有给我想要的结果。
最佳答案
使用 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())
));
但是,在这里使用嵌套的 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);
}
}
}
这利用 computeIfAbsent
来填充 map 并创建一个包含具有相同城市 ID 的每个学生的列表。
关于Java 流 - 按嵌套列表分组(按第二顺序列出),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36960226/