A general method for list object ordering in Java _java

Source: Internet
Author: User

This article describes the general method of list object sorting in Java. Share to everyone for your reference. The specific analysis is as follows:

In the list lists found in the database, often need to reorder different fields, the general practice is to use the sorted fields, back to the database query. If you do not go to the database query, directly in the first detected list of sorting, will undoubtedly improve the performance of the system.

As long as the first detected results stored in the session, you can reorder the list. You can generally use Collections.sort (list) for list sorting, but this method does not work if the list contains an object. So how do you sort it? 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 want to sort the fields of the UserInfo list, does each field write a piece of code like the one shown above? That's certainly not the result we need. Write programs to write more and more concise, can not write more redundancy. Can you write a generic method? The answer is yes, but first you have to solve the following three questions:

1. You can use generics;
2. Can use common comparison methods, such as CompareTo;
3. Are there any generic methods like generics and generic methods?

The 1th problem can be solved, the 2nd question is not very difficult, because all types of Java inherits from object, there is a method of ToString, you can convert all types to string, and then compare with CompareTo. The 3rd question is that there are no generic methods we need. But can we work out a way to use the GetMethod and invoke methods to dynamically remove the method. The complete code is as follows:

 public class sortlist<e>{public void Sort (list<e> List, final String meth
        OD, 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 ret = M2.invoke (((E) b), null). ToString (). CompareTo (M1.invo
          Ke (((E) a), null). ToString ());
        else//positive ORDER 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;
  }
     }); }
}

Look at the above code, we have successfully solved the above three problems, and also added a positive reverse. The code does not use specific objects and types, has been universal, we used a generic E, if you want to order the UserID of UserInfo, the method name can be used as a string in the form of parameters to pass in: for example, "GetUserID." You can use the code provided below to test:

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 Arraylis
    T<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 ("-------Original Sequence-------------------");
    for (UserInfo user:list) {System.out.println (user.tostring ());
    //Call Sort generic class sortlist<userinfo> sortlist = new sortlist<userinfo> ();
    Sort by userid Sortlist.sort (list, "GetUserID", "desc");
    System.out.println ("--------in reverse order by UserID------------------");
    for (UserInfo user:list) {System.out.println (user.tostring ()); }//By username sort sortlist.sort (list, "getUsername ", NULL);
    System.out.println ("---------sorted by username-----------------");
    for (UserInfo user:list) {System.out.println (user.tostring ());
    ///press Birthdate to sort Sortlist.sort (list, "Getbirthdatestr", null);
    System.out.println ("---------sorted by Birthdate-----------------");
    for (UserInfo user:list) {System.out.println (user.tostring ()); }
  }
}

The test results are as follows:

-------The original sequence-------------------
3 b; 1980-12-01
1; 1980-10-01
2; A; 1973-10-01
-------- UserID in reverse order------------------
3; b; 1980-12-01
2; A; 1973-10-01;
1; c; 1980-10-01;
--------- Sorted by username-----------------
2; A; 1973-10-01
3; b; 1980-12-01
1; 1980-10-01
-------- -Sorted by Birthdate-----------------
2; A; 1973-10-01
1; c 1980-10-01;
3; b; 1980-12-01; 11

Note: The sort of date is sorted first by format conversion, otherwise there will be no correct result.

I hope this article will help you with your Java programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.