List 中对象按属性排序

Collections.sort()方法可以对List对象进行排序,用户需要按特定属性进行排序,有两种实现方法:
1. public static <T extends Comparable<? super T>> void sort(List<T> list)
   使用Collection的这个方法,需要T类的对象实现Comparable接口,如下:


class Employee implementsComparable<Employee>{
    privateInteger pay;


    publicEmployee(int pay){
       this.pay=pay;
    }


    public void show(){
        System.out.println(pay);
    }

    @Override
    public int compareTo(Employee o) {
        return this.pay.compareTo(o.pay);
    }
}

   测试一下:

public class Test{
    publicstatic void main(String[] args) {
     List<Employee>list=new ArrayList<Employee>();
     list.add(new Employee(22));
     list.add(new Employee(1));
     list.add(new Employee(233));
     list.add(new Employee(12));
     list.add(new Employee(165));

     Collection.sort(list);
      for(Employeee:list){
         e.show();
     }

}

    输出结果如下
   1
    12
    22
    165
   233
2.public static<T> voidsort(List<T> list,Comparator<?superT> c) 

class Employer{
    private Integer age;
    public Employer(int age) {
        this.age=age;
    }
    public voidshow(){
        System.out.println(age);
    }
    publicInteger getAge(){
        return this.age;
    }
}
    测试一下

publicclass Test{

   public static void main(String[] args) {
     List<Employer> list=newArrayList<Employer>();
     list.add(new Employer(22));
     list.add(new Employer(1));
     list.add(new Employer(233));
     list.add(new Employer(12));
     list.add(newEmployer(165));
     Collections.sort(list,newComparator<Employer>() {
         @Override
         public int compare(Employer o1, Employer o2) {
             returno1.getAge().compareTo(o2.getAge());
         }
     });
     for(Employer e:list){
         e.show();
      
}

   }

}

阅读更多
个人分类: java
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭