In the develop code process, we tend to order a set of data according to requirements, of course frontend can rely on JS to sort, here is to say in backend how to sort:
To sort on the backend, we need to use the sort method of the collections class, and if you just sort a group of numbers and letters, you can use Collections.sort (list<?> List) directly, and ASC ascending by default. If you are ordering a group of complex arrays of your own definition, rewrite the comparator to rewrite it.
Look at one of the following examples:
Private final comparator<t> IDASC = new Comparator<t> () {
@Override
public int compare (t t1, T T2) {
return (int) (T1.getid ()-T2.getid ());
}
};
This is an ascending arrangement by ID of class T, and if you want to sort in descending order, you just need to change the sequence:
Private final comparator<t> Iddesc = new Comparator<t> () {
@Override
public int compare (t t1, T T2) {
return (int) (T2.getid ()-T1.getid ());
}
};
How to use:
Collections.sort (list<t> List, Comparator Comparator);
The above example is just a simple custom sort, but in the real world we may need to sort by multiple criteria. Look at the following example:
Sort by number num First, if NUM is the same and then sorted by ID
Public final comparator<t> NUMANDIDASC = new Comparator<t> () {
@Override
public int compare (t t1, T T2) {
int numdiff= t1.getnumber ()-T2.getnumber ();
int iddiff= T1.getid ()-T2.getid ();
if (numdiff== 0) {
return Iddiff;
} else {
if (Iddiff < 0) return-1;
else return 1;
}
}
};
The above example is arranged in ascending order according to two conditions, if you want to sort the descending, you can change the sequence of the comparison.
If you want to sort by more than two criteria, refine the order according to the logic of the above example.
This article is from the "Java-like teenager" blog, please make sure to keep this source http://zhengjiang.blog.51cto.com/8568971/1632891
Java rewrite the sorting method according to its own requirements