java按照集合中元素的属性进行排序示例代码

public class Student {
 private String name;
 private int age;
 private int id;
 public Student() {
  super();
 }
 public Student(String name, int age, int id) {
  super();
  this.name = name;
  this.age = age;
  this.id = id;
 }
 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 getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 @Override
 public String toString() {
  return "id:"+id+"\tage"+age+"\tname"+name;
 }
}

 

 

public class Test {
 public static void main(String[] args) {
  ArrayList<Student> list = new ArrayList<Student>();
  list.add(new Student("张三",23,1));
  list.add(new Student("张三",24,4));
  list.add(new Student("李四",22,2));
  list.add(new Student("王五",21,3));
  Collections.sort(list,new Comparator<Student>() {
   public int compare(Student s1, Student s2) {
    if(!s1.getName().equals(s2.getName())){
     return s2.getName().compareToIgnoreCase(s1.getName());
    }
    if(s1.getAge()>s2.getAge()){
     return 1;// return 1代表需要交换位置
    }
    return -1;
   }
  });
  
  for (int i = 0; i < list.size(); i++) {
   System.out.println(list.get(i).toString());
  }
 }
}

posted on 2014-08-12 15:06  狂奔的呙牛  阅读(163)  评论(0编辑  收藏  举报

导航