java中Comparator自定义排序:
Comparator接口可以实现自定义排序,实现Comparator接口时,要重写compare方法:
int compare(Object o1, Object o2) 返回一个基本类型的整型
如果要按照升序排序,则o1 小于o2,返回-1(负数),相等返回0,01大于02返回1(正数)
如果要按照降序排序,则o1 小于o2,返回1(正数),相等返回0,01大于02返回-1(负数)
**定义一个Person类,属性为姓名name,学号number,年龄age,性别sex,身高height,体重weigth,自定义排序规则为:
性别男优先
年龄从小到大
体重从低到高
身高从高到低
姓名字数从少到多**
public class PersonTest {
public static void main(String[] args) {
List<Person> list=new LinkedList<Person>();
list.add(new Person("钟爱", "201508020114", 21, "女", 162.01, 80.03));
list.add(new Person("张大旗", "20150802", 22, "女", 159.99, 102.34));
list.add(new Person("王大拿里哦", "20150802012", 20, "男", 182.01, 132));
list.add(new Person("张三", "201501", 18, "男", 144, 112));
list.add(new Person("张原野", "201505", 19, "女", 120, 144));
list.add(new Person("李冬梅子", "201503", 20, "男", 189, 122));
list.add(new Person("田园圣诞", "201504",20, "男", 189, 132));
list.add(new Person("李很帅", "201502", 17, "男", 173, 132));
for (Person person : list) {
System.out.println("排序前"+person);
}
System.out.println("========================================================================");
list.sort(new Comparator<Person>() {
int flag=0;
@Override
public int compare(Person o1, Person o2) {
int a=o1.getSex().compareTo(o2.getSex());
if(a!=0&&a>0){
return -1;
}
else if(o1.getSex().equals(o2.getSex())){
if(o1.getAge()<o2.getAge()){
return -1;
}
else if(o1.getAge()==o2.getAge()){
if(o1.getWeigth()<o2.getWeigth()){
return -1;
}
else if(o1.getWeigth()==o2.getWeigth()){
if(o1.getHeight()>o2.getHeight()){
return -1;
}
else if(o1.getHeight()==o2.getHeight()){
if(o1.getName().length()<o2.getName().length()){
return -1;
}
}
}
}
}
return 1;
}
});
for (Person person1 : list) {
System.out.println("排序后"+person1);
}
}
}