gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 11:45:04 25 4
gpt4 key购买 nike

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

请给我一个干净的方法。

最佳答案

在 Java 8 中:

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

关于java - 按属性对对象列表进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21678430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com