第一種是list中的對象實現Comparable介面,如下:
/*** 根據order對User排序*/public class User implements Comparable <user> { 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 int compareTo(User arg0) { return this.getOrder().compareTo(arg0.getOrder()); }} </user>
測試一下:
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 <user> list = new ArrayList <user> (); //此處add user2再add user1 list.add(user2); list.add(user1); Collections.sort(list); for(User u : list){ System.out.println(u.getName()); } }} </user> </user>
輸出結果如下
a
b
第二種方法是根據Collections.sort重載方法來實現,例如:
/*** 根據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 <user> list = new ArrayList <user> (); 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()); } }} </user> </user> </user>
輸出結果如下
a
b
前者代碼結構簡單,但是只能根據固定的屬性排序,後者靈活,可以臨時指定排序項,但是代碼不夠簡潔
多欄位的場合:
Collections.sort(list,new Comparator <user> (){ public int compare(User arg0, User arg1) { // 第一次比較專業 int i = arg0.getOrder().compareTo(arg1.getOrder());// 如果專業相同則進行第二次比較 if(i==0){// 第二次比較 int j=arg0.getXXX().compareTo(arg1.getXXX());// 如果學制相同則返回按年齡排序 if(j==0){ return arg0.getCCC().compareTo(arg1.getCCC()); } return j; } return i; } }); </user>
以上內容就是小編給大家介紹有關用Java集合中的Collections.sort方法如何對list排序(兩種方法),希望對大家有所協助。