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

160

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

请给我提供一个清晰的方法来完成它。


3
一个哈希映射,以位置作为键,学生列表作为值。 - Omoro
按位置排序能解决你的问题吗,还是有其他的原因? - Warlord
尝试使用 Comparator 并按位置排序。 - pshemek
1
@Warlord 是的,但是如果我需要获取像按地点分组的学生数量这样的信息,最好能够进行分组。 - Dilukshan Mahendra
我认为这里的答案https://dev59.com/oWoy5IYBdhLWcg3wkO6g#8464106也适用于这个问题。 - Fabricio Buzeto
显示剩余2条评论
13个回答

0
  @Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    KeyValuePair<?, ?> that = (KeyValuePair<?, ?>) o;
    return Objects.equals(key, that.key) && Objects.equals(value, that.value);
}

@Override
public int hashCode() {
    return Objects.hash(key, value);
}

0
你可以这样做:
Map<String, List<Student>> map = new HashMap<String, List<Student>>();
List<Student> studlist = new ArrayList<Student>();
studlist.add(new Student("1726", "John", "New York"));
map.put("New York", studlist);

键将是位置,值将是学生列表。因此,稍后您可以仅使用以下内容获取一组学生:

studlist = map.get("New York");

-1

您可以这样排序:

    Collections.sort(studlist, new Comparator<Student>() {

        @Override
        public int compare(Student o1, Student o2) {
            return o1.getStud_location().compareTo(o2.getStud_location());
        }
    });

假设你的学生类也有位置的getter方法。

5
为什么需要排序?问题是要将元素分组! - Sankalp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接