java使用Collection.sort指定升序或降序的三种方法

第一种方法,Bean中实现Comparator接口:

public class CollectionsTest {
    public static void main(String[] args) {
        List list = new ArrayList();  
       //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{
    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 list = new ArrayList();
        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{
 
    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 list = new ArrayList();
        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(){
            @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); 
     }
}

你可能感兴趣的:(java,collection)