Java API针对集合类型排序提供了两种支持:
java.util.Collections.sort(java.util.List)
java.util.Collections.sort(java.util.List, java.util.Comparator)
1种实现Comparator接口
public static void main(String[] a) {
ArrayList<P> arrayList = new ArrayList<>();
arrayList.add(new P(34, "大爷34"));
arrayList.add(new P(3, "大爷3"));
arrayList.add(new P(5, "大爷5"));
arrayList.add(new P(10, "大爷10"));
arrayList.add(new P(22, "大爷22"));
//使用 Comparator接口来实现排序
//通过int值排序
arrayList.sort(new Comparator<P>() {
@Override
public int compare(P o1, P o2) {
//o1-o2(结果是负数)升序
//o2-o1(结果是正整数)降序
return o1.age - o2.age;
}
});
//通过string来进行排序
arrayList.sort(new Comparator<P>() {
@Override
public int compare(P o1, P o2) {
//o1.name.compareTo(o2.name)升序
//o2.name.compareTo(o1.name)降序
return o1.name.compareTo(o2.name);
}
});
//Comparable排序法,要求元素实现此接口。
Collections.sort(arrayList);
for (P p : arrayList) {
System.out.println(p.name);
}
}
二种 P implements Comparable
static class P implements Comparable<P> {
P(int a, String n) {
name = n;
age = a;
}
public String name;
public int age;
@Override
public int compareTo(@NotNull P o) {
return age - o.age;
}
}
Kotlin排序
//排序
var list = mutableListOf<Person>()
list.add(Person(50, "大爷5"))
list.add(Person(60, "大爷6"))
list.add(Person(10, "大爷1"))
list.add(Person(20, "大爷2"))
//升序
// list.sortBy { it.age }
//降序
list.sortByDescending { it.age }
//多条件排序先根据age 升序排列,若age相同,根据name升序排列
list.sortWith(compareBy({ it.age }, { it.name }))
list.forEach { println(it.age) }