標籤:
要想對List進行排序,可以讓實體物件實現Comparable介面,重寫compareTo方法即可實現按某一屬性排序,但是這種寫法很單一,只能按照固定的一個屬性排序,沒變法變化。通過下面這種方法,可以動態指定List按照某一個屬性進行排序,例子很簡單,看代碼就明白了。
import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;public class testCollection { /** * @param args */ public static void main(String[] args) { User u1=new User(); u1.setName("Jessica"); u1.setAge(20); User u2=new User(); u2.setName("Abobo"); u2.setAge(30); List<User> userList=new ArrayList<User>(); userList.add(u1); userList.add(u2); MyComparator sort=new MyComparator(); MyComparator2 sort2=new MyComparator2(); MyComparator3 sort3=new MyComparator3(); MyComparator4 sort4=new MyComparator4(); Collections.sort(userList,sort); for (User u:userList) { System.out.println(u.toString()+";I am "+(userList.indexOf(u)+1)+" and I‘m ordered by Name desc"); } Collections.sort(userList,sort2); for (User u:userList) { System.out.println(u.toString()+";I am "+(userList.indexOf(u)+1)+" and I‘m ordered by Name asc"); } Collections.sort(userList,sort3); for (User u:userList) { System.out.println(u.toString()+";I am "+(userList.indexOf(u)+1)+" and I‘m ordered by Age desc"); } Collections.sort(userList,sort4); for (User u:userList) { System.out.println(u.toString()+";I am "+(userList.indexOf(u)+1)+" and I‘m ordered by Age asc"); } } public static class MyComparator implements Comparator<User>{ @Override public int compare(User o1, User o2) { return -o1.getName().compareTo(o2.getName()); } } public static class MyComparator2 implements Comparator<User>{ @Override public int compare(User o1, User o2) { return o1.getName().compareTo(o2.getName()); } } public static class MyComparator3 implements Comparator<User>{ @Override public int compare(User o1, User o2) { return -o1.getAge().compareTo(o2.getAge()); } } public static class MyComparator4 implements Comparator<User>{ @Override public int compare(User o1, User o2) { return o1.getAge().compareTo(o2.getAge()); } }}
結果:
Hello!My Name is Jessica and I‘m 20;I am 1 and I‘m ordered by Name descHello!My Name is Abobo and I‘m 30;I am 2 and I‘m ordered by Name descHello!My Name is Abobo and I‘m 30;I am 1 and I‘m ordered by Name ascHello!My Name is Jessica and I‘m 20;I am 2 and I‘m ordered by Name ascHello!My Name is Abobo and I‘m 30;I am 1 and I‘m ordered by Age descHello!My Name is Jessica and I‘m 20;I am 2 and I‘m ordered by Age descHello!My Name is Jessica and I‘m 20;I am 1 and I‘m ordered by Age ascHello!My Name is Abobo and I‘m 30;I am 2 and I‘m ordered by Age asc
通過這種方法,可以選擇為List排序的方式了,打好地基,才能逐漸穩固的長城。
Java基礎集錦——利用Collections.sort方法對list排序