如何根据对象的属性对对象进行排序?

时间:2012-12-08 01:51:48

标签: java hashmap

除了sort方法之外,我还有其他工作要做。我需要根据学生的第一个属性对HashMap中的学生进行排序。在我添加HashMap中的所有学生之后,我需要排序方法,而不是在添加时。

package HashMap;

        import java.io.InputStream;
        import java.util.HashMap;
        import java.util.HashSet;
        import java.util.Scanner;

        public class clubMapping {
            HashMap<String, HashSet<Student>> map = new HashMap<String, HashSet<Student>>();

            public clubMapping(String clubName) {
                InputStream is = getClass().getClassLoader().getResourceAsStream(
                        "student.txt");
                Scanner scan = new Scanner(is);
                while (scan.hasNext())
                    add(scan.next(), scan.next(), Integer.parseInt(scan.next()),
                            scan.next());
                scan.close();
                System.out.println(map);
                System.out.println();
                System.out.println(map.get(clubName));
            }

            public void add(String last, String first, Integer id, String club) {
                HashSet<Student> set = new HashSet<Student>();
                if (!map.containsKey(club)) {
                    set.add(new Student(last, first, id));
                    map.put(club, set);
                } else {
                    set = map.get(club);
                    set.add(new Student(last, first, id));
                }
            }

            public static void main(String[] args) {
                new clubMapping("Math");
            }
        }

    package HashMap;

    public class Student {
        String last, first;
        Integer id;

        public Student(String l, String f, Integer i) {
            last = l;
            first = f;
            id = i;
        }

        public String toString() {
            return last + " " + first + " " + id;
        }
    }

1 个答案:

答案 0 :(得分:1)

您应该为学生集使用TreeSet而不是HashSet。树集是隐式排序的,哈希集不是。

public void add(String last, String first, Integer id, String club) {
    TreeSet<Student> set = new TreeSet<Student>(studentComp);
    if (!map.containsKey(club)) {
        set.add(new Student(last, first, id));
        map.put(club, set);
    } else {
        set = map.get(club);
        set.add(new Student(last, first, id));
    }
}

但是你必须定义一个用于排序的比较器,如下所示。

private static Comparator<Student> studentComp = new Comparator<Student>() {
    @Override
    public int compare(Student s1, Student s2) {
        return (s1.last.compareTo(s2.last));
    }
};

此外,您应该将学生属性封装在getter / setter方法中,而不是直接访问它们,就像我上面所做的那样(正如您的课程目前允许的那样)。