I have a list of java object that have 4 members.
int id;
String 开发者_JAVA百科name;
String age;
int order;
I want to sort the list of this object w.r.t order
.
class Foo {
private int id;
private String name;
private String age;
private int order;
//accessors
}
Use Custom Comparator
List<Foo> list = null;
Collections.sort(list, new Comparator<Foo>() {
public int compare(Foo o1, Foo o2) {
return Integer.valueOf(o1.getOrder()).compareTo(Integer.valueOf( o2.getOrder()));
}
});
- You can Implement java.lang.Comparable interface and put the sorting logic in compareTo(T o) or else
- you can have custom java.lang.Comparator and have the logic in compare() method.
I would suggest to implement custom Comparator, as later if you try to modify your sorting criteria, ll be easily done.
Make the object implement Comparable
.
public class Person implements Comparable<Person> {
private int id;
private String name;
private int order;
public int compareTo(Person p) {
return p.order - this.order;
}
}
You can then use objects of this class Person
in any sorted list such as PriorityQueue
or you could simply use Collections.sort(personList)
for that.
Use a PriorityQueue and let your objects extend Comparable.
You also have to implement the compareTo(object o) method.
精彩评论