List<String> list = new ArrayList();list.add("刘媛媛"); list.add("王硕"); list.add("李明"); list.add("刘迪"); list.add("刘布"); //升序 Collections.sort(list,Collator.getInstance(java.util.Locale.CHINA));//注意:是根据的汉字的拼音的字母排序的,而不是根据汉字一般的排序方法 for(int i=0;i<list.size();i++) { System.out.print(list.get(i)); } System.out.println(""); //降序 Collections.reverse(list);//不指定排序规则时,也是按照字母的来排序的 for(int i=0;i<list.size();i++) { System.out.print(list.get(i)); }
结果:
李明刘布刘迪刘媛媛王硕
王硕刘媛媛刘迪刘布李明
自定义排序:
1.第一种是model类实现Comparable接口,重写重写int compareTo(Object o)方法
public class StudentDTO implements Comparable { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public ObjType getType() { return type; } public void setAge(int age) { this.age= age; } @Override public int compareTo(Object o) { StudentDTO sdto = (StudentDTO)o; int otherAge = sdto.getAge(); // note: enum-type's comparation depend on types' list order of enum method // so, if compared property is enum-type ,then its comparationfollow ObjEnum.objType order return this.age.compareTo(otherAge); } }
调用:
public static void main(String[] args) { List<StudentDTO> studentList = new ArrayList(); StudentDTO s1 = new StudentDTO (); s.setName("yuanyuan"); s.setAge(22); studentList.add(s1); StudentDTO s1 = new StudentDTO (); s.setName("lily"); s.setAge(23); studentList.add(s2); Collections.sort(studentList); //按照age升序 22,23, Collections.reverse(studentList); //按照age降序 23,22 }
model类:
public class StudentDTO implements Comparable { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public ObjType getType() { return type; } public void setAge(int age) { this.age= age; } }比较器类:
class MyCompartor implements Comparator { @Override public int compare(Object o1, Object o2) { StudentDTO sdto1= (StudentDTO )o1; StudentDTO sdto2= (StudentDTO )o2; return sdto1.getAge.compareTo(stdo2.getAge()) } }调用:
public static void main(String[] args) { List<StudentDTO> studentList = new ArrayList(); StudentDTO s1 = new StudentDTO (); s.setName("yuanyuan"); s.setAge(22); studentList.add(s1); StudentDTO s1 = new StudentDTO (); s.setName("lily"); s.setAge(23); studentList.add(s2); MyComparetor mc = new MyComparetor(); Collections.sort(studentList,mc); //按照age升序 22,23, Collections.reverse(studentList,mc); //按照age降序 23,22 }