Java tool for sorting by Object Attributes

Source: Internet
Author: User
Tags string methods

This tool class is a tool class for sorting by Object Attributes. The following functions are implemented: 1. sort by one attribute and multiple attributes of an object. 2. objects are listed in the forward and backward order of object properties. 3. perfect support for int and other basic classes and Integer packaging classes. 4. the perfect support attribute is the class that implements the Comparable interface. 5. if the class is not java. if the basic type defined in lang is not implemented, the Comparable interface is converted to String for sorting. implementation idea: Get the object attribute or object method value using reflection to remove the dependency on a specific object.

Import java. lang. reflect. field; import java. lang. reflect. invocationTargetException; import java. lang. reflect. method; import java. util. arrayList; import java. util. collections; import java. util. comparator; import java. util. date; import java. util. list;/*** sort by certain properties of the object * @ author Lee Kun * Exchange blog: http://blog.csdn.net/lk_blog */public class SortListUtil {public static final String DESC = "desc"; public Static final String ASC = "asc";/*** sort the elements in the list in ascending order. ** @ param list * sorting Set * @ param field * sorting field * @ return */public static List <?> Sort (List <?> List, final String field) {return sort (list, field, null);}/*** sorts the elements in the list. ** @ param list * sorting Set * @ param field * sorting field * @ param sort * sorting method: SortList. DESC (descending) SortList. ASC (ascending ). * @ return */@ SuppressWarnings ("unchecked") public static List <?> Sort (List <?> List, final String field, final String sort) {Collections. sort (list, new Comparator () {public int compare (Object a, Object B) {int ret = 0; try {Field f =. getClass (). getDeclaredField (field); f. setAccessible (true); Class <?> Type = f. getType (); if (type = int. class) {ret = (Integer) f. getInt ()). compareTo (Integer) f. getInt (B);} else if (type = double. class) {ret = (Double) f. getDouble ()). compareTo (Double) f. getDouble (B);} else if (type = long. class) {ret = (Long) f. getLong ()). compareTo (Long) f. getLong (B);} else if (type = float. class) {ret = (Float) f. getFloat ()). compareTo (Float) f. getFloa T (B);} else if (type = Date. class) {ret = (Date) f. get ()). compareTo (Date) f. get (B);} else if (isImplementsOf (type, Comparable. class) {ret = (Comparable) f. get ()). compareTo (Comparable) f. get (B);} else {ret = String. valueOf (f. get ()). compareTo (String. valueOf (f. get (B);} catch (SecurityException e) {e. printStackTrace ();} catch (NoSuchFieldException e) {e. printStackTrace ();} Catch (IllegalArgumentException e) {e. printStackTrace ();} catch (IllegalAccessException e) {e. printStackTrace ();} if (sort! = Null & sort. toLowerCase (). equals (DESC) {return-ret;} else {return ret ;}}); return list ;}/ *** sorts the elements in the list by fields and sorts, * fields [I] specifies the sorting field and sorts [I] specifies the sorting method. if sorts [I] is empty, sorts are sorted in ascending order by default. ** @ param list * @ param fields * @ param sorts * @ return */@ SuppressWarnings ("unchecked") public static List <?> Sort (List <?> List, String [] fields, String [] sorts) {if (fields! = Null & fields. length> 0) {for (int I = fields. length-1; I> = 0; I --) {final String field = fields [I]; String tmpSort = ASC; if (sorts! = Null & sorts. length> I & sorts [I]! = Null) {tmpSort = sorts [I];} final String sort = tmpSort; Collections. sort (list, new Comparator () {public int compare (Object a, Object B) {int ret = 0; try {Field f =. getClass (). getDeclaredField (field); f. setAccessible (true); Class <?> Type = f. getType (); if (type = int. class) {ret = (Integer) f. getInt ()). compareTo (Integer) f. getInt (B);} else if (type = double. class) {ret = (Double) f. getDouble ()). compareTo (Double) f. getDouble (B);} else if (type = long. class) {ret = (Long) f. getLong ()). compareTo (Long) f. getLong (B);} else if (type = float. class) {ret = (Float) f. getFloat ()). compareTo (Float) f. getFloa T (B);} else if (type = Date. class) {ret = (Date) f. get ()). compareTo (Date) f. get (B);} else if (isImplementsOf (type, Comparable. class) {ret = (Comparable) f. get ()). compareTo (Comparable) f. get (B);} else {ret = String. valueOf (f. get ()). compareTo (String. valueOf (f. get (B);} catch (SecurityException e) {e. printStackTrace ();} catch (NoSuchFieldException e) {e. printStackTrace ();} Catch (IllegalArgumentException e) {e. printStackTrace ();} catch (IllegalAccessException e) {e. printStackTrace ();} if (sort! = Null & sort. toLowerCase (). equals (DESC) {return-ret;} else {return ret ;}}) ;}} return list ;} /*** the default order is ** @ param list * @ param method * @ return */public static List <?> SortByMethod (List <?> List, final String method) {return sortByMethod (list, method, null) ;}@ SuppressWarnings ("unchecked") public static List <?> SortByMethod (List <?> List, final String method, final String sort) {Collections. sort (list, new Comparator () {public int compare (Object a, Object B) {int ret = 0; try {Method m =. getClass (). getMethod (method, null); m. setAccessible (true); Class <?> Type = m. getReturnType (); if (type = int. class) {ret = (Integer) m. invoke (a, null )). compareTo (Integer) m. invoke (B, null);} else if (type = double. class) {ret = (Double) m. invoke (a, null )). compareTo (Double) m. invoke (B, null);} else if (type = long. class) {ret = (Long) m. invoke (a, null )). compareTo (Long) m. invoke (B, null);} else if (type = float. class) {ret = (Float) m. invoke (A, null )). compareTo (Float) m. invoke (B, null);} else if (type = Date. class) {ret = (Date) m. invoke (a, null )). compareTo (Date) m. invoke (B, null);} else if (isImplementsOf (type, Comparable. class) {ret = (Comparable) m. invoke (a, null )). compareTo (Comparable) m. invoke (B, null);} else {ret = String. valueOf (m. invoke (a, null )). compareTo (String. valueOf (m. invoke (B, null);} if (isImpleme NtsOf (type, Comparable. class) {ret = (Comparable) m. invoke (a, null )). compareTo (Comparable) m. invoke (B, null);} else {ret = String. valueOf (Mbps. invoke (a, null )). compareTo (String. valueOf (m. invoke (B, null);} catch (NoSuchMethodException ne) {System. out. println (ne);} catch (IllegalAccessException ie) {System. out. println (ie);} catch (InvocationTargetException it) {System. out. println (it) ;} If (sort! = Null & sort. toLowerCase (). equals (DESC) {return-ret;} else {return ret ;}}); return list ;}@ SuppressWarnings ("unchecked") public static List <?> SortByMethod (List <?> List, final String methods [], final String sorts []) {if (methods! = Null & methods. length> 0) {for (int I = methods. length-1; I> = 0; I --) {final String method = methods [I]; String tmpSort = ASC; if (sorts! = Null & sorts. length> I & sorts [I]! = Null) {tmpSort = sorts [I];} final String sort = tmpSort; Collections. sort (list, new Comparator () {public int compare (Object a, Object B) {int ret = 0; try {Method m =. getClass (). getMethod (method, null); m. setAccessible (true); Class <?> Type = m. getReturnType (); if (type = int. class) {ret = (Integer) m. invoke (a, null )). compareTo (Integer) m. invoke (B, null);} else if (type = double. class) {ret = (Double) m. invoke (a, null )). compareTo (Double) m. invoke (B, null);} else if (type = long. class) {ret = (Long) m. invoke (a, null )). compareTo (Long) m. invoke (B, null);} else if (type = float. class) {ret = (Float) m. invoke (A, null )). compareTo (Float) m. invoke (B, null);} else if (type = Date. class) {ret = (Date) m. invoke (a, null )). compareTo (Date) m. invoke (B, null);} else if (isImplementsOf (type, Comparable. class) {ret = (Comparable) m. invoke (a, null )). compareTo (Comparable) m. invoke (B, null);} else {ret = String. valueOf (m. invoke (a, null )). compareTo (String. valueOf (m. invoke (B, null);} catch (No SuchMethodException ne) {System. out. println (ne);} catch (IllegalAccessException ie) {System. out. println (ie);} catch (InvocationTargetException it) {System. out. println (it);} if (sort! = Null & sort. toLowerCase (). equals (DESC) {return-ret;} else {return ret ;}}) ;}} return list ;} /*** determine whether all interfaces implemented by the object contain szInterface ** @ param clazz * @ param szInterface * @ return */public static boolean isImplementsOf (Class <?> Clazz, Class <?> SzInterface) {boolean flag = false; Class <?> [] Face = clazz. getInterfaces (); for (Class <?> C: face) {if (c = szInterface) {flag = true;} else {flag = isImplementsOf (c, szInterface) ;}} if (! Flag & null! = Clazz. getSuperclass () {return isImplementsOf (clazz. getSuperclass (), szInterface);} return flag;} public static void main (String [] args) throws Exception {List <Student> list = new ArrayList <Student> (); list. add (new Student (3, "B", 1, new Date (11110000); list. add (new Student (1, "c", 3, new Date (44440000); list. add (new Student (2, "a", 2, new Date (22210000); list. add (new Student (4, "a", 11, new Date (33330000); System. out. println ("------- original sequence -------------------"); for (Student stu: list) {System. out. println (stu. toString ();} // sort by age in the forward order. Note that the result is, and 11. it is not, (if the String type is in ascending order) SortListUtil. sort (list, "age", null); System. out. println ("--------- test Integer and positive order, sort by age in positive order ---------------"); for (Student stu: list) {System. out. println (stu. toString ();} // sort by id in reverse order SortListUtil. sort (list, "id", SortListUtil. DESC); System. out. println ("-------- test int and inverted, in descending order of id ------------------"); for (Student stu: list) {System. out. println (stu. toString ();} // sort by name in the forward order, and then SortListUtil in the forward order of id. sort (list, new String [] {"name", "id"}, new String [] {}); System. out. println ("--------- test multiple sorting fields, first in the forward order of name, and then in the forward order of id -----------------"); for (Student stu: list) {System. out. println (stu. toString ();} // sort by name in the forward order and then SortListUtil in the reverse order of id. sort (list, new String [] {"name", "id"}, new String [] {SortListUtil. ASC, SortListUtil. DESC}); System. out. println ("--------- test multiple sorting fields, first in the forward order of name, and then in the reverse order of id -----------------"); for (Student stu: list) {System. out. println (stu. toString ();} // sort SortListUtil by birthday. sort (list, "birthday"); System. out. println ("--------- test achieves the Comparable interface object sorting, by the birthday positive order -----------------"); for (Student stu: list) {System. out. println (stu. toString ();} // sortByMethod SortListUtil. sortByMethod (list, "getId", null); System. out. println ("--------- test sortByMethod, in the forward order of the getId method -----------------"); for (Student stu: list) {System. out. println (stu. toString ());}}}

 

Test execution result: Studeng. java:
import java.util.*;    public class Student{      private int id;        private String name;        private Integer age;        private Date birthday;        public Student(int id, String name, Integer age, Date birthday) {          super();          this.id = id;          this.name = name;          this.age = age;          this.birthday = birthday;      }        public int getId() {          return id;      }        public void setId(int id) {          this.id = id;      }        public String getName() {          return name;      }        public void setName(String name) {          this.name = name;      }        public Integer getAge() {          return age;      }        public void setAge(Integer age) {          this.age = age;      }        public Date getBirthday() {          return birthday;      }        public void setBirthday(Date birthday) {          this.birthday = birthday;      }        @Override      public String toString() {          return "Student [id=" + id + ", name=" + name + ", age=" + age                  + ", birthday=" + birthday + "]";      }      }  

 


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.