在Java中按两个字段对列表进行分组。

huangapple go评论80阅读模式
英文:

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&lt;Student&gt; list = map.get(key);
			list.add(student);

		}else{
			List&lt;Student&gt; list = new ArrayList&lt;Student&gt;();
			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&lt;Object&gt; key = Arrays.asList(city, country);

Replace your Long key ... line with this (and update map's type accordingly), e.g.

Map&lt;List&lt;Object&gt;, List&lt;Student&gt;&gt; map = new HashMap&lt;&gt;();

(List&lt;Object&gt; 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)

huangapple
  • 本文由 发表于 2020年4月6日 05:34:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/61049821.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定