由于之前基本都是用c++写算法,导致java排序库函数非常不熟悉,记录一下java库函数排序方法
基本数据类型的排序
public static void main(String[] args) {
Integer[] a = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5};
Arrays.sort(a);
for (Integer integer : a) {
System.out.print(integer + " ");
}
}
运行结果:0 1 2 3 4 5 6 7 8 9
默认为升序,手动改成降序需要自己实现Comparator接口
public class Main{
public static void main(String[] args) {
Integer[] a = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5};
Comparator<Integer> cmp = new MyComparator();
Arrays.sort(a,cmp);
for (Integer integer : a) {
System.out.print(integer + " ");
}
}
}
class MyComparator implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
}
运行结果:9 8 7 6 5 4 3 2 1 0
但是大部分时候还是类排序偏多,类一般会放进list里面,所以再来研究一下List排序
public class Main{
public static void main(String[] args) {
//进行一个先按名字字典降序排序,如果名字一样,按id升序排序
Student stu1 = new Student(0, "tom");
Student stu2 = new Student(1, "tom");
Student stu3 = new Student(2, "zoo");
Student stu4 = new Student(3, "abc");
List<Student> list = new ArrayList<Student>();
list.add(stu4);list.add(stu3);list.add(stu2);list.add(stu1);
Collections.sort(list);
for (Student student : list) {
System.out.println(student);
}
}
}
class Student implements Comparable<Student>{
public int id;
public String name;
public Student() {
}
public Student(int id,String name) {
this.id = id;
this.name = name;
}
@Override
public int compareTo(Student o) {
if(this.name.equals(o.name)){
return id > o.id ? 1 : -1;//把1和-1的位置换一下就是id的降序
}else{
//this.name.compareTo(o.name)就是字典升序
return o.name.compareTo(this.name);
}
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}
}
运行结果:
Student [id=2, name=zoo]
Student [id=0, name=tom]
Student [id=1, name=tom]
Student [id=3, name=abc]