public class Test {
public static void main(String[] args) {
/**
* 集合类的排序大同小异,以List为例,List的排序分两种情况
*
* 一:指定泛型为内置类,如Integer,String,BigDecimal等(集合数组Map等无法比较的除外)
*/
List<String> list = new ArrayList<>();
// 1,Collections工具类排序
Collections.sort(list);// 升序排列
Collections.reverse(list);// 反向排列(与reverseOrder()不同)
Collections.shuffle(list);// 随机排列
// 2,Comparator比较器排序,Collections.sort(list,comparator)同list.sort(comparator)
Collections.sort(list, Collator.getInstance(Locale.CHINA));// 中文排序(包括数字英文)
Collections.sort(list, Comparator.naturalOrder());// 升序排列
Collections.sort(list, Comparator.reverseOrder());// 降序排列
Collections.sort(list, Comparator.nullsFirst(Comparator.naturalOrder()));// null优先的升序排列
Comparator<String> comparator = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
// 自定义排序规则,o1与o2相比,大的返回正数,小的返回负数,相等返回0
return o1.compareTo(o2);// 按字典顺序比较字符串(数字和英文)
}
};
list.sort(comparator);// 自定义比较器排序
/**-------------------------------------------------------
* 二:指定泛型为自定义类(如Student)
*
* 该类需实现Comparable接口并重写compareTo方法
* 然后定义方法的返回值,两个对象相比,大的返回正数,小的返回负数,相等返回0
*/
List<Student> list2 = new ArrayList<Student>();
list2.add(new Student("波澜哥", 14, 34));
list2.add(new Student("面筋哥", 16, 55));
list2.add(new Student("高音哥", 12, 73));
list2.add(new Student("娇喘哥", 18, 20));
// compareTo方法只是定义排序规则,仍然要调用相应排序方法执行排序
Collections.sort(list2);
// 此时仍可结合比较器进行比较,最终结果以比较器里的排序规则为主
Collections.sort(list2, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
// 自定义排序规则,o1与o2相比,大的返回正数,小的返回负数,相等返回0
if (o1.getStuAge2() > o2.getStuAge2()) {
return 1;
} else if (o1.getStuAge2() < o2.getStuAge2()) {
return -1;
}
return 0;
}
});
list2.forEach(stu -> System.out.print(stu.getStuAge()
+ stu.getStuName() + stu.getStuAge2() + " "));
}
/**
* ------------------------Student-----------------------------
*/
static class Student implements Comparable<Student> {
// 实现Comparable<T>接口,重写compareTo()方法,在该方法中自定义排序规则
private String stuName;
private int stuAge;
private int stuAge2;
public Student(String stuName, int stuAge, int stuAge2) {
this.stuAge = stuAge;
this.stuAge2 = stuAge2;
this.stuName = stuName;
}
@Override
public int compareTo(Student stu) {
// 自定义排序规则,本类与方法参数stu相比,大的返回正数,小的返回负数,相等返回0
if (this.getStuAge() > stu.getStuAge()) {
return 1;
} else if (this.getStuAge() < stu.getStuAge()) {
return -1;
}
return 0;// 相等返回0
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getStuAge() {
return stuAge;
}
public void setStuAge(int stuAge) {
this.stuAge = stuAge;
}
public int getStuAge2() {
return stuAge2;
}
public void setStuAge2(int stuAge2) {
this.stuAge2 = stuAge2;
}
}
}