List集合中的对象进行排序
类A:
public class A implements Comparable<A>{ private Integer id; private String name; public A(){ } public A(Integer id , String name){ this.id = id; this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString(){ return "id:" + id + ";name:" + name; } @Override public int compareTo(A o) { //正序 return o.getId().compareTo(this.getId()); //倒序 //return this.getId().compareTo(o.getId()); } }
类B:
public class B { private Integer id; private String name; public B(){ } public B(Integer id , String name){ this.id = id; this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString(){ return "id:" + id + ";name:" + name; } }
(1)对象的类实现 Comparable 接口,直接调用,就可以实现排序
Collections.sort(list);
(2)sort(List<T> list, Comparator<? super T> c)
Collections.sort(list2, new Comparator<B>() { @Override public int compare(B o1, B o2) { //正序 // return o1.getId().compareTo(o2.getId()); //倒序 return o2.getId().compareTo(o1.getId()); } });