简介
首先要明白comparator是升序排序的。
简单来说就是return o1 - o2时,是升序排序的。
return -(o1-o2) 就是逆序排序的。
comparator返回负值时,o1会排在o2前面。
返回正值时,o1会排在o2后面。
逆序代码
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class SortTest {
public static void main(String[] args) {
List<Integer> arr = new ArrayList<>();
arr.add(5);
arr.add(9);
arr.add(3);
System.out.println(arr);
Collections.sort(arr, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return - (o1 - o2);
}
});
System.out.println(arr);
}
}
代码示例
package edu.sjtu.ist.comutil;
import java.util.Comparator;
class Student {
private String name;
private int age;
private float score;
public Student(String name, int age, float score) {
this.name = name;
this.age = age;
this.score = score;
}
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 float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
public String toString()
{
return name+"\t\t"+age+"\t\t"+score;
}
}
class StudentComparator implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
if(o1.getScore()>o2.getScore())
return -1;
else if(o1.getScore()<o2.getScore())
return 1;
else{
if(o1.getAge()>o2.getAge())
return 1;
else if(o1.getAge()<o2.getAge())
return -1;
else
return 0;
}
}
}
public class ComparableDemo02 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Student stu[]={new Student("zhangsan",20,90.0f),
new Student("lisi",22,90.0f),
new Student("wangwu",20,99.0f),
new Student("sunliu",22,100.0f)};
java.util.Arrays.sort(stu,new StudentComparator());
for(Student s:stu)
{
System.out.println(s);
}
}
}