Reference: 151 recommendations for improving Java code-73 recommendations: sorting using Compatator
In Java, there are two ways to sort the data:
- Implementing the Comparable interface
- Implementing the Comparator interface
In the JDK class library, a subset of the classes implement the comparable interface, such as Integer double and string.
The comparable interface has a Comparto (Object O) method that returns an integer type. For expression X.compareto (y), if the return value is 0, then x and y are equal, and if the return value is greater than 0, then X is greater than Y, and if the return value is less than 0, X is less than Y.
View comparable interface source code
Public Interface Comparable<t> { publicint compareTo (T o);}
As an example:
Sort your company's staff, sort by job number, first define an employee class
Write the employee class to implement the comparable interface
PackageHello;ImportOrg.apache.commons.lang3.builder.CompareToBuilder;ImportOrg.apache.commons.lang3.builder.ToStringBuilder; Public classEmployeeImplementsComparable<employee>{ //IDs are encoded according to the order in which they enter the company. Private intID; //name PrivateString name; //Job Title PrivatePosition Position; PublicEmployee (intID, String name, Position Position) { Super(); This. ID =ID; This. Name =name; This. Position =position; } //Sort by ID number, which is the depth of seniority@Override Public intcompareTo (Employee o) {//TODO auto-generated Method Stub return NewComparetobuilder (). Append (ID, o.id). Tocomparison (); } @Override PublicString toString () {returnTostringbuilder.reflectiontostring ( This); } Public intgetId () {returnID; } Public voidSetId (intID) { This. ID =ID; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicPosition getPosition () {returnposition; } Public voidsetposition (Position Position) { This. Position =position; }}
This is a simple JavaBean, which describes an employee's basic information, where the ID is the employee number, according to the order of entry into the company code, position is the job description, is the manager or the general Staff, this is an enumeration type:
Public enum Position { Boss, manager,staff}
There are three levels of positions:
Boss (owner), manager, Staff
The CompareTo () method of the employee class is the method that the comparable interface must implement, implemented using Apach's tool class, indicating that it is sorted by the natural sequence of IDs (ascending). After everything is ready, let's see how to sort:
PackageHello;Importjava.util.ArrayList;Importjava.util.Collections;ImportJava.util.Comparator;Importjava.util.List; Public classHelloword { Public Static voidMain (string[] args) {List<Employee> list =NewArraylist<employee> (5); //a bossList.add (NewEmployee (1001, "Zhang San", Position.boss)); //Two managersList.add (NewEmployee (1006, "Zhao Si", Position.manager)); List.add (NewEmployee (1003, "Harry", Position.manager)); //Two EmployeesList.add (NewEmployee (10002, "Li Liu", Position.staff)); List.add (NewEmployee (1005, "Ma Niu"), Position.staff)); //sort by id, i.e. sort by seniorityCollections.sort (list); for(Employee e:list) {System.out.println (e); } }}
"Run Results":
[Email protected] [Id=1001,name= Zhang San, position=boss] [Email protected] [Id=1003,name= Harry, Position=manager] [Email protected] [Id=1005,name= Horse Ox, Position=staff] [Email protected] [Id=1006,name= Zhao Four, Position=manager] [Email protected] [Id=10002,name= Li Liu, Position=staff]
is sorted by ID in ascending order and the result is correct.
The spirit of "leadership first" concept, according to the position from high to low sort, first the boss, then the manager, and finally the General Staff, employee has been a stable class, in order to a sorting function to modify it, the impact of sorting by ID, not a good way.
The Collections.sort () method has an overloaded method of sort (list<t> List, comparator<? super t> C), there is a Comparator interface parameter, we implement this interface:
// Position Sequencer class Implements Comparator<employee>{ @Override publicint Compare (Employee O1, Employee O2) { // in descending order of position return o1.getposition (). CompareTo ( O2.getposition ()); }
Created a position ranking method, sorted by job rank, and tested:
New positioncomparator ()); for (Employee e:list) { System.out.println (e); }
"Run Results":
[Email protected] [Id=1001,name= Zhang San, position=boss] [Email protected] [Id=1003,name= Harry, Position=manager] [Email protected] [Id=1006,name= Zhao Four, position=manager]hello[email protected][id=1005,name= ma niu, position=staff][email protected][id= 10002,name= Li Liu, Position=staff]
Sorted by position, the result is correct.
- Sort by position from lowest to highest
In order to take care of employees, you need to sort by position from low to high
Two ways:
- Collections.reverse (list<?> List) method for descending order
- Collections.sort (list<?> list,collections.reverseorder (New Positioncomparator ()) can also
Use these two methods to test:
collections.reverse (list); for (Employee e:list) { System.out.println (e); } System.out.println ("----"); Collections.sort (list, collections.reverseorder (new Positioncomparator ())); for (Employee e:list) { System.out.println (e); }
"Run Results":
[Email protected] [Id=10002,name= Li Liu, position=staff][email protected][id=1005,name= ma niu, position=staff][email protected] [ID=1006,name= Zhao Four, position=manager][email protected][id=1003,name= Harry, position=Manager][email Protected][id=1001,name= Zhang San, position=Boss]----[email protected][id=10002,name= Li Liu, position =staff][email protected][id=1005,name= ma niu, position=staff][emailprotected][id =1006,name= Zhao Four, position=manager][email protected][id=1003,name= Harry, position=manager][email protected][id= 1001, Name= Zhang San, position=boss]
According to the position from the ground to the high sort, the result is correct
- Sort by position first, same position by ID
In the CompareTo or compare method, first determine whether the position is equal, the position is equal and then sorted by work number
Modify the CompareTo () method of the Employee class to
@Override publicint compareTo (Employee o) { return New Comparetobuilder () . Append (position, o.position) // Sort by position // work number sort }
Sort code:
Collections.sort (list); for (Employee e:list) { System.out.println (e); }
"Run Results":
[Email protected] [Id=1001,name= Zhang San, position=boss][email protected][id=1006,name= Zhao Four, position=Manager][email protected] [ID=1003,name= Harry, position=manager][email protected][id=1005,name= ma niu, position=staff][email Protected][id=1002,name= Li Liu, Position=staff]
Summarize:
- The comparable interface class is implemented to show that it can be compared and can be sorted by comparison.
- The comparator interface is a tool class interface that is used as a comparison and has no relation to the logic of the original class;
Java Object Comparison Sort