当前位置: 首页 > 知识库问答 >
问题:

按属性将对象列表分组

宋明亮
2023-03-14

我需要使用特定对象的属性(位置)对对象列表(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;
    }
}

请给我一个干净的方法。


共有3个答案

厉熠彤
2023-03-14
Map<String, List<Student>> map = new HashMap<String, List<Student>>();

for (Student student : studlist) {
    String key  = student.stud_location;
    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);
    }

}
麹繁
2023-03-14

这将把students对象添加到HashMap中,并将locationID作为键。

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。

曾飞雨
2023-03-14

在Java 8中:

Map<String, List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));
 类似资料:
  • 问题内容: 我需要使用特定对象的属性(位置)对对象(学生)列表进行分组,代码如下所示, 请给我建议一个干净的方法。 问题答案: In Java 8:

  • 问题内容: 我正在尝试读取文件,并用逗号在每行中拆分一个单元格,然后仅显示包含有关纬度和经度信息的第一和第二个单元格。这是文件: 时间, 纬度,经度 ,类型2015-03-20T10:20:35.890Z, 38.8221664,-122.7649994 ,地震 2015-03-20T10 :18:13.070Z, 33.2073333,-116.6891667 ,地震 2015-03-20T10

  • 我试图分裂链接的图像是什么错在我的代码

  • 问题内容: 如何转换为: 到这个: 使用javascript或下划线 问题答案: 假设原始列表包含在名为的变量中:

  • 我有一个对象列表,我需要按其中一个对象属性对其进行排序。 我可以用下面的代码按升序排序 但是,这是按升序排序列表,而我需要做的是按降序排序。在对对象列表进行排序时,这可能吗?

  • 问题内容: 我想使用Java 8技巧在一行中执行以下操作。 给定此对象定义: 和a ,我想得到a ,它是第一个列表中所有s对象的列表- 顺序相同。 我可以使用Java中的循环来做到这一点,但我相信Java8中应该有一个单行lambda可以做到这一点。我无法在线找到解决方案。也许我没有使用正确的搜索词。 有人可以为这种转换建议一个lambda或另一种线吗? 问题答案: 这应该可以解决问题: 也就是说