about the Collections in the Sort Use of methods
In Java, if you want to sort a collection object or array object, you need to implement the comparator interface to achieve the goal that we want.
This ordering is guaranteed to be stable: no reordering of equal elements is made by invoking the Sort method.
As an example:
Defines a user class with the name and score two properties.
Define a arrylist , whose inner element is User object, how to follow User of the score sort in ascending order?
Declaring the user type
Public class User {
Public String name;
Public int score;
Public User (String name,int score)
{
this. Name =name;
this. Score = score;
}
}
Sort by the score of the user object, sorted in ascending order. Need to inherit comparator interface
Public class Comparator implements comparator<user>{
Public int Compare (User u1,user U2)
{
return U1.score-u2.score;
}
};
Public class Main {
Public Static void Main (string[] args) {
TODO auto-generated Method stub
arraylist<user> list = new arraylist<user> ();
List.add (new User ("Wangqiang", 100));
List.add (new User ("Lizeyang", 99));
List.add (new User ("Linyenan", 78));
List.add (new User ("Yaojianliang", 80));
List.add (new User ("Xinhong", 66));
List.add (new User ("gaoming", 66));
List.add (new User ("Liupeng", 87));
Collections. Sort (list,new Comparator ());
for (User index:list)
{
System. out. println (Index.score + index.name);
}
}
}
The final sort result is:
66gaoming
78linyenan
80yaojianliang
87liupeng
99lizeyang
100wangqiang
In addition, if you follow the Name property of the User object in descending order, then modify the Compare class as follows:
Public class Comparator implements comparator<user>{
Public int Compare (User u1,user U2)
{
return u2.name.compareTo (u1.name);
}
};
The descending result is:
Xinhong66
wangqiang100
Lizeyang99
liupeng87
Linyenan78
Gaoming66
If the element itself is comparable, and ascending. Then the default Collections.sort (Object) can be implemented.
But if you need a descending order, then you have to modify the Compare method. For example, a string object
Use of comparator in Java