The list sort is broadly divided into the following two categories:
1,list<integer> to Integer, string and other types of List sort
2.list<object> Sorting of custom objects
The code example in this article is only a simple introduction, only play a role, the reader can develop their own ha.
1. Sort the list<integer>
The code is as follows:
1list<integer> L =NewArraylist<integer>();2L.add (3);3L.add (1);4L.add (2);5L.add (9);6L.add (7);7 8Collections.sort (l);//default sort (small to large)9 for(inti:l) {Ten System.out.println (i); One } A -Collections.reverse (l);//flashbacks (from big to small) - for(inti:l) { the System.out.println (i); -}
After the code runs, the result is 12379 97321 , which is the output of the flashback (from the largest to the smallest).
2. Sort the list<object>
To sort the custom objects, first the object needs to implement the comparable interface, and then override the CompareTo method. The code is as follows:
Entity Objects :
1 /*2 * Student Entity3 */4 classStudentImplementsComparable<student>{5 PublicInteger Age = 0;6 PublicString Name = "";7 8 PublicInteger getage () {9 returnAge ;Ten } One Public voidSetage (intAge ) { AAge =Age ; - } - the PublicString GetName () { - returnName; - } - Public voidsetName (String name) { +Name =name; - } + A PublicStudent (intage,string name) { at This. Age =Age ; - This. Name =name; - } - - @Override - Public intCompareTo (Student s) { in //The Custom comparison method returns 1 if the entity itself is considered large, or 1 - if( This. Age >=S.getage ()) { to return1; + } - return-1; the } *}
Sort Code Instance : can be sorted by LIst.sort () or by Collections.sort () , the result is the same
1list<student> list =NewArraylist<student>();2 3List.add (NewStudent (1, "Zhangsan"));4List.add (NewStudent (6, "Zhangsan"));5List.add (NewStudent (2, "Zhangsan"));6List.add (NewStudent (9, "Zhangsan"));7List.add (NewStudent (1, "Zhangsan"));8 9List.sort (Comparator.naturalorder ());//Positive sequence comparisonTen //Collections.sort (list);//Positive sequence comparison One A for(Student i:list) { - System.out.println (I.getage ()); -}
The code writes only a positive order, and the result is as follows:11269.
The overall sort of simple implementation is such a son, there are many shortcomings, I hope you greatly correct me. ^_^!!
Java List Sort