第一种方法,Bean中实现Comparator接口
public class CollectionsClass {
/**
* @param args
*/
public static void main(String[] args) {
List<BeanClass> list = new ArrayList<BeanClass>(); //BeanClass 需实现Comparable接口
BeanClass bc1 = new BeanClass();
BeanClass bc2 = new BeanClass();
bc1.para = 1;
bc2.para = 2;
list.add(bc1);
list.add(bc2);
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 {
/**
* @param args
*/
public static void main(String[] args) {
List<BeanClass> list = new ArrayList<BeanClass>();
BeanClass bc1 = new BeanClass();
BeanClass bc2 = new BeanClass();
bc1.para = 1;
bc2.para = 2;
list.add(bc1);
list.add(bc2);
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 bc1, BeanClass bc2) {
//return bc1.para-bc2.para; //升序
return bc2.para-bc1.para; //降序
}
}
public class CollectionsClass {
/**
* @param args
*/
public static void main(String[] args) {
List<BeanClass> list = new ArrayList<BeanClass>();
BeanClass bc1 = new BeanClass();
BeanClass bc2 = new BeanClass();
bc1.para = 1;
bc2.para = 2;
list.add(bc1);
list.add(bc2);
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);
}
}
注:
public int compare(Object o1, Object o2) 返回一个基本类型的整型
如果要按照升序排序,
则o1 小于o2,返回-1(负数),相等返回0,01大于02返回1(正数)
如果要按照降序排序
则o1 小于o2,返回1(正数),相等返回0,01大于02返回-1(负数)