问题
Is there any kind of utility method to sort Lists like the following one:
POJO pojo1 = new POJO();
pojo1.setFoo("abc");
POJO pojo2 = new POJO();
pojo2.setFoo("abc");
List theList = new ArrayList<POJO>();
theList.add(pojo1);
theList.add(pojo2);
SortUtils.sort(theList, "foo", SortType.ALPHABETICAL, SortDirection.ASC)
EDIT: Thanks for your answers but I know that you can make the POJO implement Comparable or use Collections.sort(list, Comparator) but creating an anonymous class looks like overwhelming for quick sorting needs, I'm looking for something like an utility method that uses reflection to access attribute values and sort elements
回答1:
Collections.sort and implement comparable on pojo or pass in a comparator to the sort method.
回答2:
Implement Comparable(In the same class) or Comparator( In any seperate class if you dont have the source code of the class you want to sort) and then call Collections.sort
回答3:
Sticking to the core fundamentals can really help in this case , use comparable , for some extended logic use comparator , tried tested and efficient .
Thanks Abhi
回答4:
Use the Comparable interface to create a list, ArrayList, and the sort method of Collections, Collections.sort().
Inside the compareTo() method you can use your logic to order the list.
http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
http://onjava.com/onjava/2003/03/12/java_comp.html
As an addedum, you can use the variant that takes a Comparator as an argument:
http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List, java.util.Comparator)
来源:https://stackoverflow.com/questions/10302005/any-utility-method-to-sort-java-util-list-containing-pojos-of-the-kind-of-apache