1. 程式人生 > >Java中對list集合進行排序

Java中對list集合進行排序

原文連結

/**
* 根據order對User排序
*/
public class User { //此處無需實現Comparable介面
    private String name;
    private Integer order;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getOrder() {
        return order;
    }
    public void setOrder(Integer order) {
        this.order = order;
    }
}

主類中這樣寫即可: 
public class Test{
    public static void main(String[] args) {
        User user1 = new User();
        user1.setName("a");
        user1.setOrder(1);
        User user2 = new User();
        user2.setName("b");
        user2.setOrder(2);
        List list = new ArrayLis ();
        list.add(user2);
        list.add(user1); 
        Collections.sort(list,new Comparator<User> (){
            public int compare(User arg0, User arg1) {
                return arg0.getOrder().compareTo(arg1.getOrder());
            }
        });
        for(User u : list){
            System.out.println(u.getName());
        }
    }
}
     
輸出結果如下 
a
b