按属性对对象列表进行分组

新手上路,请多包涵

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

 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;
    }
}

请建议我一个干净的方法来做到这一点。

原文由 Dilukshan Mahendra 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 481
2 个回答

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

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

遍历 此代码并将学生添加到 HashMap

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

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

如果您希望所有学生都有特定的位置详细信息,那么您可以使用:

 hashMap.get(locationId);

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

原文由 Dileep 发布,翻译遵循 CC BY-SA 4.0 许可协议

在 Java 8 中:

 Map<String, List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));

原文由 Vitalii Fedorenko 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题