按属性对对象列表进行分组 [英] Group a list of objects by an attribute

查看:120
本文介绍了按属性对对象列表进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用特定对象的属性(Location)对对象列表(Student)进行分组.代码如下:

I need to group a list of objects (Student) using an attribute (Location) of the particular object. The code is like below:

public class Grouping {
    public static void main(String[] args) {

        List<Student> studlist = new ArrayList<Student>();
        studlist.add(new Student("1726", "John", "New York"));
        studlist.add(new Student("4321", "Max", "California"));
        studlist.add(new Student("2234", "Andrew", "Los Angeles"));
        studlist.add(new Student("5223", "Michael", "New York"));
        studlist.add(new Student("7765", "Sam", "California"));
        studlist.add(new Student("3442", "Mark", "New York"));

    }
}

class Student {
    String stud_id;
    String stud_name;
    String stud_location;

    Student(String sid, String sname, String slocation) {
        this.stud_id = sid;
        this.stud_name = sname;
        this.stud_location = slocation;
    }
}

请建议我采用一种干净的方法.

Please suggest me a clean way to do it.

推荐答案

这会将学生对象添加到

This will add the students object to the HashMap with locationID as key.

HashMap<Integer, List<Student>> hashMap = new HashMap<Integer, List<Student>>();

迭代此代码,并将学生添加到HashMap:

Iterate over this code and add students to the HashMap:

if (!hashMap.containsKey(locationId)) {
    List<Student> list = new ArrayList<Student>();
    list.add(student);

    hashMap.put(locationId, list);
} else {
    hashMap.get(locationId).add(student);
}

如果您希望所有学生都具有特定的位置详细信息,则可以使用以下方法:

If you want all the student with particular location details then you can use this:

hashMap.get(locationId);

这将为您提供具有相同位置ID的所有学生.

which will get you all the students with the same the location ID.

这篇关于按属性对对象列表进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆