要想对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 desc Hello!My Name is Abobo and I'm 30;I am 2 and I'm ordered by Name desc Hello!My Name is Abobo and I'm 30;I am 1 and I'm ordered by Name asc Hello!My Name is Jessica and I'm 20;I am 2 and I'm ordered by Name asc Hello!My Name is Abobo and I'm 30;I am 1 and I'm ordered by Age desc Hello!My Name is Jessica and I'm 20;I am 2 and I'm ordered by Age desc Hello!My Name is Jessica and I'm 20;I am 1 and I'm ordered by Age asc Hello!My Name is Abobo and I'm 30;I am 2 and I'm ordered by Age asc
通过这种方法,可以选择为List排序的方式了,打好地基,才能逐渐稳固的长城。