针对list里对象属性的排序问题

来源:互联网 发布:天津关键字优化公司 编辑:程序博客网 时间:2024/05/16 04:59
import java.util.Date;

public class Customer{
   private String name;
   private int    age;
   private int lev;
   private Date   inTime; 
   
   public Customer(String name, int age, int lev, Date inTime) {
super();
this.name = name;
this.age = age;
this.lev = lev;
this.inTime = inTime;
   }
  public Customer() {
super();
  }
  public String getName() {
return name;
  }

  public void setName(String name) {
this.name = name;
  }
   public int getAge() {
return age;
   }
   public void setAge(int age) {
this.age = age;
  }
  public int getLev() {
return lev;
  }
  public void setLev(int lev) {
this.lev = lev;
  }
  public Date getInTime() {
return inTime;
  }
  public void setInTime(Date inTime) {
this.inTime = inTime;
  }
   

}


import java.util.Comparator;

public class ComparatorCus implements  Comparator {
@Override
public int compare(Object o1, Object o2) {
Customer cus1 = (Customer)o1;
Customer cus2 = (Customer)o2;

                //排序的优先级是等级、再是时间
int flag = cus1.getLev()-cus2.getLev(); //若不是int类型,可以这样比较int flag = cus1.getLev().compareTo(cus2.getLev());
if(flag==0){//等级相等
return (cus1.getInTime().after(cus2.getInTime()))==true?1:-1;
}else{
return flag;
}

}

}


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class SortCusTest {

public static void main(String[] args) throws Exception {
List<Customer> list = new ArrayList<Customer>();
SimpleDateFormat formater= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
list.add(new Customer("zhang",20,1,formater.parse("2015-3-23 10:10:00")));
list.add(new Customer("wang",22,2,formater.parse("2015-3-23 10:10:10")));
list.add(new Customer("li",19,2,formater.parse("2015-3-23 10:10:05")));
list.add(new Customer("zhao",30,1,formater.parse("2015-3-23 10:10:08")));
list.add(new Customer("chang",20,2,formater.parse("2015-3-23 10:10:15")));

ComparatorCus copm = new ComparatorCus();
Collections.sort(list, copm);
for(Customer c:list){
System.out.println("Name:"+c.getName()+", Lev:"+c.getLev()+", Date:"+formater.format(c.getInTime()));
}
}

}


结果:

Name:zhang, Lev:1, Date:2015-03-23 10:10:00
Name:zhao, Lev:1, Date:2015-03-23 10:10:08
Name:li, Lev:2, Date:2015-03-23 10:10:05
Name:wang, Lev:2, Date:2015-03-23 10:10:10
Name:chang, Lev:2, Date:2015-03-23 10:10:15

0 0