天天看點

集合對象根據某個屬性值進行排序

import java.util.Collections;

import java.util.Comparator;

public class Test {

    public static void main(String[] args) throws Exception {

        //Student是一個對象,該對象中有個帶參數的構造方法

        List<Student> ps = new ArrayList<Student>();

        ps.add(new Student("h", "啊"));

        ps.add(new Student("a", "中"));

        ps.add(new Student("c", "寶"));

        System.out.println("排序前");

        for (Student o : ps) {

            System.out.println(o.getValue().charAt(0)+" "+o.getName());

        }

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

            @Override

            public int compare(Student o1, Student o2) {

                //String類型進行排序

                return return o1.getValue().compareTo(o2.getValue());

            }

        });

        System.out.println("排序後");

        for (Student o : ps) {

            System.out.println(o.getValue().charAt(0)+" "+o.getName());

        }

    }

}