第一种方法,Bean中实现Comparator接口:
public class CollectionsTest {
public static void main(String[] args) {
List<BeanClass> list = new ArrayList<BeanClass>();
//BeanClass 需实现Comparable接口
BeanClass bean1 = new BeanClass();
BeanClass bean2 = new BeanClass();
bean1.para = 1;
bean2.para = 2;
list.add(bean1;
list.add(bean2);
Collections.sort(list);
System.out.println(list.get(0).para);
System.out.println(list.get(1).para);
}
}
BeanClass类
public class BeanClass implements Comparable<BeanClass>{
int para;
public int compareTo(BeanClass bc) {
// return this.para - bc.para; //升序
return bc.para-this.para; //降序
}
}
第二种方法,自定义比较器
public class CollectionsClass {
public static void main(String[] args) {
List<BeanClass> list = new ArrayList<BeanClass>();
BeanClass bean1 = new BeanClass();
BeanClass bean2 = new BeanClass();
bean1.para = 1;
bean2.para = 2;
list.add(bean1);
list.add(bean2);
Collections.sort(list,new MyComparator());
System.out.println(list.get(0).para);
System.out.println(list.get(1).para);
}
}
MyComparator类
public class MyComparator implements Comparator<BeanClass>{
public int compare(BeanClass bean1, BeanClass bean2) {
//return bean1.para-bean2.para; //升序
return bean2.para-bean1.para; //降序
}
}
第三种,和第二种一样,不过使用匿名类
public class CollectionsClass {
public static void main(String[] args) {
List<BeanClass> list = new ArrayList<BeanClass>();
BeanClass bean1 = new BeanClass();
BeanClass bean2 = new BeanClass();
bean1.para = 1;
bean2.para = 2;
list.add(bean1);
list.add(bean2);
Collections.sort(list,new Comparator<BeanClass>(){
@Override
public int compare(BeanClass o1, BeanClass o2) {
// return o1.para - o2.para; //升序
return o2.para - o1.para; //降序
}
});
System.out.println(list.get(0).para);
System.out.println(list.get(1).para);
}
}