Import Java.util.arraylist;import java.util.collections;import java.util.comparator;import java.util.List;/** * * <p> * ClassName collectionssort * </p> * <p> * Description mainly introduces the sorting algorithm of two sets <br/> * First: Java.util.Colle Ctions.sort (java.util.List), requires that the ordered element must implement 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 a sort of int type attribute, The string property can be sorted using the following methods <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/> * &G T;=0 a>b; * </p> * * @author Wangxu [email protected] * <p> * Date 2014-9-16 04:52:57 * </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", List.add (c), C = new Cat ("B"), List.add (c), C = new Cat ("C", 3), List.add (c);//Ascending output collections . sort (list); SYSTEM.OUT.PRINTLN (list);//Descending sort output collections.sort (list, Collections.reverseorder ()); SYSTEM.OUT.PRINTLN (list);} public static void Method2 () {list<cat> List = new arraylist<cat> (); Cat C = new Cat ("A", List.add (c), C = new Cat ("B"), 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);//descending sort Output 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 () {}pub Lic 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;} Implement the comparable interface, do not override the 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 ();} Implement the comparator interface, you need to override the method @overridepublic int compare (cat O1, cat O2) {//TODO auto-generated method Stubreturn O1.getage ( )-O2.getage ();}}
Two ways to sort collections in Java