有时候我们会对集合中的对象进行排序,而且这个排序是根据自身系统的业务来排序的。这个时候需要自己重写排序的具体业务。
在java中 我们可以实现Comparator接口,重写该接口的comapre方法即可
比如现在有以下需求, 对Student学生对象中的身高属性进行升序排序,如果身高一样就按照id降序排列。
实例如下:
package com.xiu.compare;
public class Student {
private Integer id;
// 学生年龄
private Integer age;
// 学生姓名
private String name;
// 学生的身高
private Integer height;
/**
* 重写toString()方法
*/
@Override
public String toString() {
// TODO Auto-generated method stub
return "ID:" + this.id + ",年龄" + age + ",姓名" + name + ",身高"
+ this.height;
}
public Student() {
}
public Student(Integer id, Integer age, String name, Integer height) {
this.id = id;
this.age = age;
this.name = name;
this.height = height;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
}
比较器类
package com.xiu.compare;
import java.util.Comparator;
/**
* 先判断身高,如果身高相等再判判断id
*
* @author Administrator
*
*/
public class StudentComparator implements Comparator<Student> {
public int compare(Student s1, Student s2) {
if (s1.getHeight() > s2.getHeight()) {
return 1;
} else if (s1.getHeight() == s2.getHeight()) {
if (s1.getId() > s2.getId()) {
return 1;
} else if (s1.getId() == s2.getId()) {
return 0;
} else {
return -1;
}
} else {
return -1;
}
}
}
测试类
package com.xiu.compare;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TestComparator {
public static void main(String[] args) {
List<Student> users = new ArrayList<Student>();
Student s1 = new Student(2,10,"zgh",187);
Student s2 = new Student(1,10,"ss",175);
Student s3 = new Student(4,20,"tt",180);
Student s4 = new Student(3,30,"ss",180);
users.add(s1);
users.add(s2);
users.add(s3);
users.add(s4);
StudentComparator sc = new StudentComparator();
Collections.sort(users,sc);
for (Student student : users) {
System.out.println(student);
}
}
}
运行结果
ID:1,年龄10,姓名ss,身高175
ID:4,年龄20,姓名tt,身高180
ID:3,年龄30,姓名ss,身高180
ID:2,年龄10,姓名zgh,身高187