英文:
Grouping a List by two fields in Java
问题
// 我有一个名为 Student 的类。它包含城市、姓名和国家字段。我有一个包含 Student 对象的 ArrayList。
// 我想做的是根据城市和国家字段对学生对象进行分组。我可以像这样使用一个属性来做到:
for (Student student : studentList) {
Long key = student.country;
if (map.containsKey(key)) {
List<Student> list = map.get(key);
list.add(student);
} else {
List<Student> list = new ArrayList<Student>();
list.add(student);
map.put(key, list);
}
}
英文:
I have a Student class. It contains the city, name and country fields.I have an ArrayList that contains Student objects. What I want to do is to group student objects with city and country fields. I can do it with one attribute like this
But how can i do both name and country? Do you have any idea? I am using java 7.
for (Student student: studentList) {
Long key = student.country;
if(map.containsKey(key)){
List<Student> list = map.get(key);
list.add(student);
}else{
List<Student> list = new ArrayList<Student>();
list.add(student);
map.put(key, list);
}
}
答案1
得分: 1
使用一些允许您支持多个值的关键类型,例如:
List<Object> key = Arrays.asList(city, country);
将您的 Long key ...
行替换为以下内容(并相应更新 map
的类型),例如:
Map<List<Object>, List<Student>> map = new HashMap<>();
(List<Object>
实际上在这里不是一个很好的选择,这只是一种权宜之计:我会使用类似于特定的 CityAndCountry
类,例如使用 Google 的 AutoValue
进行定义。)
英文:
Use some key type which allows you to support multiple values, for example:
List<Object> key = Arrays.asList(city, country);
Replace your Long key ...
line with this (and update map
's type accordingly), e.g.
Map<List<Object>, List<Student>> map = new HashMap<>();
(List<Object>
is actually not a great choice here, it's merely expedient: I'd use something like a specific CityAndCountry
class, defined for example using Google's AutoValue
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论