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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值