Article title: Java List Sort the tool class by the specified field.
Article Address: http://blog.csdn.net/5iasp/article/details/17717179
Includes the following classes
1. Entity class
Package com.newyear.wish;
/**
* Entity class * * */public class Video {public video
(int id, String title, int hits) {
super ();
This.id = ID;
this.title = title;
This.hits = hits;
}
private int id;
Private String title;
private int hits;
public int getId () {return
ID;
}
public void setId (int id) {
this.id = ID;
}
Public String GetTitle () {return
title;
}
public void Settitle (String title) {
this.title = title;
}
public int gethits () {return
hits;
}
public void sethits (int hits) {
this.hits = hits;
}
}
2. List Sort Tool class
Package com.newyear.wish;
Import Java.lang.reflect.Method;
Import java.util.ArrayList;
Import java.util.Collections;
Import Java.util.Comparator;
Import java.util.List; /** * List by the specified field Sort tool class * * @param <T> * * public class Listsortutil<t> {/** * @param targetlist Target sort Li St * @param sortfield sort field (Entity Class Property name) * @param sortmode sort (ASC or DESC)/@SuppressWarnings ({"Unchecked", "Rawtyp Es "}" public void sort (list<t> targetlist, final string SortField, final string sortmode) {Collections.sort (T
Argetlist, New Comparator () {public int compare (object Obj1, Object obj2) {int retVal = 0;
The try {//First letter is capitalized String newstr=sortfield.substring (0, 1). toUpperCase () +sortfield.replacefirst ("\\w", "");
String methodstr= "Get" +NEWSTR;
Method method1 = ((T) obj1). GetClass (). GetMethod (METHODSTR, NULL);
Method method2 = ((T) obj2). GetClass (). GetMethod (METHODSTR, NULL); if (SortMode!= null && "desc". Equals (SortMode){RetVal = Method2.invoke ((((t) obj2), null). ToString (). CompareTo (Method1.invoke ((((()) obj1), null). ToString ()); Reverse} else {retVal = Method1.invoke (((t) obj1), null). ToString (). CompareTo (Method2.invoke (((()) obj2), null. ToS Tring ());
Positive sequence} catch (Exception e) {throw new RuntimeException ();
return retVal;
}
});
}
}
3. Test class
Package com.newyear.wish;
Import java.util.ArrayList;
Import java.util.List;
public class Listsortutiltest {
/**
* @param args
*
/public static void main (string[] args) {
list& Lt video> targetlist = new arraylist<video> ();
Targetlist.add (New video (1, "title1");
Targetlist.add (New video (2, "title2");
Targetlist.add (New Video (3, "Title3");
System.out.println ("Sort before:" + targetlist);
listsortutil<video> sortlist = new listsortutil<video> ();
Sortlist.sort (TargetList, "hits", "ASC");
System.out.println ("After sort:" +targetlist);
}
Test Execution Results:
Sort before: [com.newyear.wish.video@c17164, Com.newyear.wish.video@1fb8ee3, Com.newyear.wish.video@61de33]
Sort after: [Com.newyear.wish.video@1fb8ee3, com.newyear.wish.video@c17164, Com.newyear.wish.video@61de33]