Go directly to the code:
import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;/** * * <p> * ClassName CollectionsSort * </p> * <p> * Description Mainly introduces two sorting algorithms for collections<br/> * First: java.util.Collections.sort(java.util.List), which requires that the sorted elements must implement the java.lang.Comparable interface<br/> * Second: java.util.Collections.sort(java.util.List, java.util.Comparator), this method requires the implementation of the java.util.Comparator interface<br/> * Third: The following example uses int Type attribute sorting, you can use the following methods to sort String attributes<br/> * public int compareTo(Cat o){return this.getName().compareTo(o.getName(0);}<br/> * Fourth: Description of compareTo() function<br/> * If result;<br/> * <0 a<b;<br/>= * ==0 a==b;<br/> * >=0 a>b; * </p> * * @author wangxu [email protected] * <p> * Date 2014-9-16 04:52:57 PM * </p> * @version V1.0 * */public class CollectionsSort {public static void main(String[] args) {// method1(); test the first method method2(); // test the second method} public static void method1() {List<Cat > list = new ArrayList<Cat>();Cat c = new Cat("a", 10);list.add(c);c = new Cat("b", 20);list.add(c);c = new Cat("c", 3);list.add(c);// Sort the output in ascending order Collections.sort(list);System.out.println(list); // Sort the output in descending order Collections.sort(list, Collections.reverseOrder());System.out.println(list);} public static void method2() {List<Cat> list = new ArrayList<Cat>();Cat c = new Cat("a", 10);list.add(c);c = new Cat("b", 20);list.add(c);c = new Cat ("c", 3);list.add(c);Comparator<Cat> catComparator = new Cat();//Ascending order output Collections.sort(list, catComparator);System.out.println(list);// Sort output in descending order catComparator = Collections.reverseOrder(catComparator);Collections.sort(list, catComparator);System.out.println(list);}}class Cat implements Comparable <Cat>, Comparator<Cat> {private int age;private String name;public Cat() {}public Cat(String name, int age) {this.age = age;this.name = name;}public int getAge() {return this.age;}public String getName() {return this.name;}public void setAge(int age) {this.age = age;}public void setName(String name) {this.name = name;}// Implements the Comparable interface, do not override this method @Overridepublic int compareTo(Cat o) {// TODO Auto-generated method stubreturn this.age - o.age;}@Overridepublic String toString() {// TODO Auto-generated method stubreturn "Name: " + getName() + ",Age: " + getAge();}// Implemented Comparator interface, you need to override this method @Overridepublic int compare(Cat o1, Cat o2) {// TODO Auto-generated method stubreturn o1.getAge() - o2.getAge();}}