list java中List對象通用排序算法
/** * 學生實體類 * @author chenchuang * */ public class Student { public Student(int id, String name, int age) { super(); this.id = id; this.name = name; this.age = age; } private int id; private String name; private int age; 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 int getAge() { return age; } public void setAge(int age) { this.age = age; } }
工具類:
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * List對象排序的通用方法 * * @author chenchuang * * @param <E> */ public class ListSort<E> { /** * * @param list 要排序的集合 * @param method 要排序的實體的屬性所對應的get方法 * @param sort desc 為正序 */ public void Sort(List<E> list, final String method, final String sort) { // 用內部類實現排序 Collections.sort(list, new Comparator<E>() { public int compare(E a, E b) { int ret = 0; try { // 獲取m1的方法名 Method m1 = a.getClass().getMethod(method, null); // 獲取m2的方法名 Method m2 = b.getClass().getMethod(method, null); if (sort != null && "desc".equals(sort)) { ret = m2.invoke(((E)b), null).toString().compareTo(m1.invoke(((E)a),null).toString()); } else { // 正序排序 ret = m1.invoke(((E)a), null).toString().compareTo(m2.invoke(((E)b), null).toString()); } } catch (NoSuchMethodException ne) { System.out.println(ne); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ret; } }); } }
測試類:
import java.util.ArrayList; public class ListTest { /** * @param args */ public static void main(String[] args) { ArrayList<Student> list= new ArrayList<Student>(); list.add(new Student(1,"張三",5)); list.add(new Student(2,"李四",4)); list.add(new Student(3,"王五",3)); list.add(new Student(4,"小明",2)); list.add(new Student(5,"小黑",1)); ListSort<Student> listSort= new ListSort<Student>(); listSort.Sort(list, "getAge", "desc"); for(Student s:list){ System.out.println(s.getId()+s.getName()+s.getAge()); } } }
測試結果
1張三5 2李四4 3王五3 4小明2 5小黑1
本文由用戶 SimoneNewco 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!