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

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

问题描述

我需要使用特定对象的属性(位置)对对象列表(学生)进行分组,代码如下所示,

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 {

    /**
     * @param args the command line arguments
     */
    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"));

        //Code to group students by location
        /*  Output should be Like below
            ID : 1726   Name : John Location : New York
            ID : 5223   Name : Michael  Location : New York
            ID : 4321   Name : Max  Location : California
            ID : 7765   Name : Sam  Location : California    

         */

        for (Student student : studlist) {
            System.out.println("ID : "+student.stud_id+"\t"+"Name : "+student.stud_name+"\t"+"Location : "+student.stud_location);
        }


    }
}

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.

推荐答案

这会将学生对象添加到 HashMap locationID 作为键。

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

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

对此代码进行迭代并将学生添加到 HashMap

if (!hashMap.containsKey(locationId)) {
    List<Location> list = new ArrayList<Location>();
    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.

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

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