Java排序方法

由於之前基本都是用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]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章