下面的代码实现了
1. 使用 Collections.sort 对 ArrayList 从大到小排序
2. 使用 PriorityQueue 对自定义的person类排序,要求:age小的靠前,age一样,名字长的靠前
public class SortTest {
public static void main(String[] args) {
int[] arr = {5, 2, 3, 6, 9, 1};
ArrayList<Integer> arrayList = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
arrayList.add(arr[i]);
}
// collections 排序
Collections.sort(arrayList);
System.out.println(arrayList);
// collections 排序+比较器
Collections.sort(arrayList, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// 返回负数:o1 o2
return o2-o1;
}
});
System.out.println(arrayList);
// PriorityQueue+比较器
// 年龄越小越靠前,年龄一样,名字越长越靠前
PriorityQueue<Person> persons = new PriorityQueue<Person>(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
if(o1.age != o2.age){
return o1.age - o2.age;
} else {
return o2.name.length() - o1.name.length();
}
}
});
persons.add(new Person("john", 38));
persons.add(new Person("marry", 38));
persons.add(new Person("li", 30));
while (!persons.isEmpty()) {
System.out.println(persons.poll());
}
}
}
class Person {
String name;
Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
比较器
new Comparator<Person>() { @Override public int compare(Person o1, Person o2) { if(o1.age != o2.age){ return o1.age - o2.age; } else { return o2.name.length() - o1.name.length(); } }
当返回负数时 o1在前面,可记:负数是o1 o2