A common method for sorting List objects in Java

  • 2020-04-01 03:50:05
  • OfStack

This article illustrates a common method for sorting List objects in Java. Share with you for your reference. Specific analysis is as follows:

In the database to find out the list list, often need to reorder the different fields, the general practice is to use the sort of fields, to the database query. If you don't have a database query, you will definitely improve the performance of your system by sorting the list directly from the first time you look it up.

Once the results of the first search are stored in session, the list can be reordered. Sorting lists is generally possible using collections.sort (list), but this is not possible if the list contains an object. So how do we sort this? If you have a UserInfo object, include the following fields:


private java.lang.Integer userId;
private java.lang.String username;
private java.util.Date birthDate;
private java.lang.Integer age;

So now to sort the userId, you might use the following method:  


Collections.sort(list, new Comparator() {
 public int compare(Object a, Object b) {
  int one = ((Order)a).getUserId ();
  int two = ((Order)b).getUserId ();
  return one- two ;
 }
});

So, if you were to sort the fields in the UserInfo list, would you write the code shown above for each field? That's certainly not the result we need. Write programs that are more and more concise, not more and more redundant. Can you write a general method? The answer is yes, but first three questions must be answered:

1. You can use generics;
2. Ability to use common comparison methods, such as compareTo;
3. Are there generic methods like generic methods or generic methods?

The first problem can be solved, and the second problem is not too difficult, because all types of Java inherit from Object, and there is a ToString method, so you can convert all types ToString for a moment, and then compare them with compareTo. The third problem is that we do not yet have the generic approach we need. However, can we be flexible and use getMethod and invoke methods to dynamically fetch the method out? Complete the code as follows:


public class SortList<E>{
  public void Sort(List<E> list, final String method, final String sort){
    Collections.sort(list, new Comparator() {
      public int compare(Object a, Object b) {
        int ret = 0;
        try{
          Method m1 = ((E)a).getClass().getMethod(method, null);
          Method m2 = ((E)b).getClass().getMethod(method, null);
          if(sort != null && "desc".equals(sort))//Reverse order
            ret = m2.invoke(((E)b), null).toString().compareTo(m1.invoke(((E)a), null).toString());
          else//Positive sequence
            ret = m1.invoke(((E)a), null).toString().compareTo(m2.invoke(((E)b), null).toString());
        }catch(NoSuchMethodException ne){
          System.out.println(ne);
        }catch(IllegalAccessException ie){
          System.out.println(ie);
        }catch(InvocationTargetException it){
          System.out.println(it);
        }
        return ret;
      }
     });
  }
}

Take a look at the code above to see if we have successfully solved the three problems above and added the reverse order. There is no specific object or type used in the code, which is already generic. We use a generic E, if we want to sort the userId of UserInfo, we can pass the method name in the form of a string with parameters: for example, "getUserId". You can test this with the following code:


//Test.java
package test;
import java.util.ArrayList;
import java.util.List;
import java.text.SimpleDateFormat;
public class Test {
  public static void main(String[] args)throws Exception{
    List<UserInfo> list = new ArrayList<UserInfo>();
    SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
    list.add(new UserInfo(3,"b",formater.parse("1980-12-01"),11));
    list.add(new UserInfo(1,"c",formater.parse("1980-10-01"),30));
    list.add(new UserInfo(2,"a",formater.parse("1973-10-01"),11));
    System.out.println("------- The original sequence -------------------");
    for(UserInfo user : list){
      System.out.println(user.toString());
    }
    //Call the sort generic class
    SortList<UserInfo> sortList = new SortList<UserInfo>();
    //Sort by userId
    sortList.Sort(list, "getUserId", "desc");
    System.out.println("-------- According to the userId Reverse order ------------------");
    for(UserInfo user : list){
      System.out.println(user.toString());
    }
    //Sort by the username
    sortList.Sort(list, "getUsername", null);
    System.out.println("---------Sort by the username-----------------");
    for(UserInfo user : list){
      System.out.println(user.toString());
    }
    //Sort by the birthDate
    sortList.Sort(list, "getBirthDatestr", null);
    System.out.println("---------Sort by the birthDate-----------------");
    for(UserInfo user : list){
      System.out.println(user.toString());
    }
  }
}

The test results are as follows:


------- The original sequence -------------------
3; b; 1980-12-01; 11
1; c; 1980-10-01; 30
2; a; 1973-10-01; 11
-------- According to the userId Reverse order ------------------
3; b; 1980-12-01; 11
2; a; 1973-10-01; 11
1; c; 1980-10-01; 30
--------- According to the username The sorting -----------------
2; a; 1973-10-01; 11
3; b; 1980-12-01; 11
1; c; 1980-10-01; 30
--------- According to the birthDate The sorting -----------------
2; a; 1973-10-01; 11
1; c; 1980-10-01; 30
3; b; 1980-12-01; 11

Note: dates are sorted by format conversion, otherwise they will not have the correct results.

I hope this article has been helpful to your Java programming.


Related articles: