When I was working on JDBC, I suddenly felt that order-by was used too much and it was not fresh. My sixth sense told me that java had encapsulated the sorting of linear tables, in eclipse, click ". ", haha, actually there is such a static method public static <T> void sort (List <T> list, Comparator <? Super T> c ).
Modify record: add another method according to @ mythabc's suggestion.
Method 1: Comparator.
Benefit: This method is flexible when running. If you want to replace the sorting rule, you can directly create another comparator without changing the original comparator, and change the New Class Name of the comparator on the client, this is close to the open and closed principle. After multiple comparator instances are accumulated, various sorting rules can be converted at will, which is nice. Model and sorting separation are closer to the single responsibility principle.
1. define a model first:
User(String userName, .userName =.userAge = .userName = setUserAge(.userAge =
2. Define a Comparator to implement the java. util. Comparator interface and write comparison rules in the compare () method:
ComparatorUser Comparator<User> flag = (flag == 0 arg0.getUserAge() -
3. When sorting, use the sort (List list List, Comparator c) method in java. util. Collections:
<User> userList = ArrayList<User> userList.add( User("A", 15 User("B", 14 User("A", 14 Collections.sort(userList, + " " +
4. Running result:
A 141514
Method 2: implement the Comparable interface.
Benefits: the model can be directly attached with sortable attributes, without defining new classes (without defining comparator). This reduces the number of classes, facilitates management, and makes reading easier.
1. define a model and implement the Comparable interface. Compile the comparison rules in the compareTo () method:
Student Comparable<Student> Student(String studentName, .studentName =.studentAge = .studentName = setStudentAge(.studentAge = flag = (flag == 0 .getStudentAge() -
2. When sorting, use the sort (List list) method in java. util. Collections:
<Student> studentList = ArrayList<Student> studentList.add( Student("A", 15 Student("B", 14 Student("A", 14 + " " +
3. Running result:
A 141514