Day03 代码

//set去重(list集合–>set集合)

public class SetMethod {
    public static void main(String[] args) {
        List<Integer> list1 = new ArrayList<>();
        list1.add(1);
        list1.add(3);
        list1.add(1);
        list1.add(2);
        list1.add(5);
        Set<Integer> set = new HashSet<>();
        set.addAll(list1);
        list1.clear();//先清空之后再添加所有 
        list1.addAll(set);
        Collections.sort(list1);//Collections.sort();参数是List集合
        System.out.println(list1);
    }
}

//外部比较器:Comparator

public class SortMethod1 {
    public static void main(String[] args) {
        List<Student> stu = new ArrayList<>();
        stu.add(new Student("liusan",20,90.0F));
        stu.add(new Student("lisi",22,90.0F));
        stu.add(new Student("wangwu",20,99.0F));
        stu.add(new Student("wangwu",22,100.F));
        Collections.sort(stu, new Comparator<Student>() {//参数里面包含一个匿名
            @Override
            public int compare(Student o1, Student o2) {
                double result = o2.getScore() - o1.getScore();//o1-o2升序排列
                if (result == 0) {                            //o2-o1降序排列
                    result = o1.getAge() - o2.getAge();
                } return (int) result;
            }
        });
        System.out.println(stu);
    }
}

//内部比较器:差异:需要有一个学生类连接Comparable接口

public class SortMethod2 {
    public static void main(String[] args) {
        List<Student> stu = new ArrayList<>();
        stu.add(new Student("liusan",20,90.0F));
        stu.add(new Student("lisi",22,90.0F));
        stu.add(new Student("wangwu",20,99.0F));
        stu.add(new Student("wangwu",22,100.F));
        Collections.sort(stu);
        System.out.println(stu);
    }
}

public class Student implements Comparable<Student> {
    private String name;
    private int age;
    private double score;
    
    public Student(String name, int age, double score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }
	//覆盖重写Comparable
    @Override
    public int compareTo(Student o) {
        double result = o.getScore() - this.getScore();//this.-o.升序
        if (result == 0) {							//o.-this.降序
            result = this.getAge() - o.getAge();
	
        } return (int) result;
    }

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值