1.Collections(集合中对象为Integer可直接使用此方法不用重写)
Collections是为集合提供的工具类
集合排序的方法为sort(List list),作用是对集合中的元素排序
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
list.add((int)(Math.random()*100));
}
System.out.println("排序前:"+ list);
Collections.sort(list);
System.out.println("排序后:" + list);
}
2.对象排序问题
使用Collections方法排序的集合元素必须实现Comparable接口。
如果元素为对象,那么可以通过实现Comparable的compareTo方法为对象添加比较逻辑
//编写学生类
public class Student implements Comparable{
.
.
.
@Override
public int compareTo(Object o) {
Student student = (Student) o;
return this.score - student.score;
}
}
//编写测试类
List<Student> list = new ArrayList<Student>();
list.add(new Student("zhang3",32));
list.add(new Student("li4",35));
list.add(new Student("wang5",98));
list.add(new Student("zhao6",85));
System.out.println("排序前:" + list);
Collections.sort(list);
System.out.println("排序后:" + list);
以上的方法是会永久改变我的Collections中的sort方法,如果我只想临时修改一次排序方法,则采用以下方法
1.接口回调问题
如果需要临时变换比较规则,则采用接口回调方式
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getScore() - o2.getScore();
}
});
2.lambda表达式
//2.lambda表达式
Collections.sort(persons, (o1, o2) -> o1.getSalary() < o2.getSalary() ? 1 : (o1.getSalary().equals(o2.getSalary()) ? 0 : -1));