The Java Collection Tool class collections provides two sorts of methods, namely:
- Collections.sort (List List)
- Collections.sort (List list,comparator c)
The first is called the natural sort, the object that participates in the order implements the comparable interface, overrides its CompareTo () method, implements the comparison size rule of the object in the method body, the example is as follows:
Entity classes: (Basic attribute, Getter/setter method, parameter-free construction method, tostring method)
1 Packagetest;2 3 Public classEmpImplementsComparable {4 5 PrivateString name;6 Private intAge ;7 PublicString GetName () {8 returnname;9 }Ten Public voidsetName (String name) { One This. Name =name; A } - Public intGetage () { - returnAge ; the } - Public voidSetage (intAge ) { - This. Age =Age ; - } + PublicEmp () { - Super(); + } A PublicEMP (String name,intAge ) { at Super(); - This. Name =name; - This. Age =Age ; - } - @Override - PublicString toString () { in return"Emp [name=" + name + ", age=" + Age + "]"; - } to @Override + Public intcompareTo (Object o) { - if(OinstanceofEmp) { theEMP emp =(EMP) o; * //return This.age-emp.getage ();//Sort by age ascending $ return This. Name.compareto (Emp.getname ());//change name Ascending sortPanax Notoginseng } - Throw NewClassCastException ("Cannot convert to an EMP type Object ..."); the } + A}
The second kind is called the custom sort, or the custom sorts, needs to write the anonymous inner class, first new one comparator interface comparator object C, simultaneously realizes compare () its method;
Then the comparator object C is passed to the parameter list of the Collections.sort () method, and the sorting function is implemented.
Description: The first method is not flexible enough, the entity class implements the comparable interface, will increase the coupling, if the different locations in the project need to call the sorting method according to different attributes, you need to repeatedly modify the comparison rules (by name or by age), the two can only choose one, Conflict. The second is a good solution to the problem. Where needed, create an instance of the inner class, overriding its comparison method.
The JUNIT4 unit test class code is as follows:
1 Packagetest;2 3 Importjava.util.ArrayList;4 Importjava.util.Collections;5 ImportJava.util.Comparator;6 Importjava.util.List;7 8 ImportOrg.junit.BeforeClass;9 Importorg.junit.Test;Ten One Public classTestsort { A - StaticList List =NewArrayList (); - //@BeforeClass annotation annotations are performed before other test methods are executed . the //and only once [email protected] annotation Callout method will be executed before each test method; - //the initialization of the collection here takes only one time, so use @beforeclass. - @BeforeClass - Public Static voidinit () { +List.add (NewEMP ("Tom", 18)); -List.add (NewEMP ("Jack", 20)); +List.add (NewEMP ("Rose", 15)); AList.add (NewEMP ("Jerry", 17)); atSystem.out.println ("Before sorting:"); - for(Object o:list) { - System.out.println (o); - } - } - in /**Sort by age ascending*/ - //@Test to //Public void Testsortage () { + //Collections.sort (list); - //System.out.println ("Natural Sort by Age:"); the //For (Object o:list) { * //System.out.println (o); $ // }Panax Notoginseng // } - // the /**Sort Ascending by name*/ + @Test A Public voidTestsortname () { the Collections.sort (list); +System.out.println ("Natural sort is sorted by name in ascending order:"); - for(Object o:list) { $ System.out.println (o); $ } - } - the /**sort by age in ascending order using the comparator comparer*/ - @TestWuyi Public voidTestcomparatorsortage () { theCollections.sort (list,NewComparator () { - @Override Wu Public intCompare (Object O1, Object O2) { - if(O1instanceofEMP && O2instanceofEmp) { AboutEMP e1 =(EMP) O1; $EMP e2 =(EMP) O2; - returnE1.getage ()-e2.getage (); - } - Throw NewClassCastException ("Cannot convert to EMP type"); A } + }); theSystem.out.println ("After using the comparator comparer in ascending order of age:"); - for(Object o:list) { $ System.out.println (o); the } the } the /**sort by name in ascending order using the comparator comparer*/ the @Test - Public voidTestcomparatorsortname () { inCollections.sort (list,NewComparator () { the @Override the Public intCompare (Object O1, Object O2) { About if(O1instanceofEMP && O2instanceofEmp) { theEMP e1 =(EMP) O1; theEMP e2 =(EMP) O2; the returne1.getname (). CompareTo (E2.getname ()); + } - Throw NewClassCastException ("Cannot convert to EMP type"); the }Bayi }); theSystem.out.println ("After using the comparator comparer sorted by name:"); the for(Object o:list) { - System.out.println (o); - } the } the the}
Right-click Blank position, Run as-> JUnit test->
The results of the operation are as follows:
before sorting: Emp [name=tom, age=18]emp [Name=jack, age=20]emp [Name=rose, age=15]emp [Name=jerry, age=17] Natural sort is sorted by name ascending: EMP [name=jack, age=20]emp [Name=jerry, age=17]emp [Name=rose, age=15]emp [Name=tom, age=18] by using the comparator comparer in ascending order of age: EMP [name=rose, age=15]emp [Name=jerry, age=17]emp [Name=tom, age=18]emp [Name=jack, age=20] When you sort by name in ascending order by using the comparator comparer: EMP [name=jack, age=20]emp [Name=jerry, age=17]emp [Name=rose, age=15]emp [Name=tom, Age=18]
Two ways to sort a Java collection