Java集合元素比较的实现

用Collection是工具类的sort()方法排序

  1. 自定义元素:为类添加比较功能,实现Comparable接口,重写compareTo方法
    对自定义Student类按年龄升序排序 ,代码如下:
public class Student implements Comparable {
    @Override
    public int compareTo(Object o) {
        Student stu=(Student)o;
        return this.age-stu.age;
    }
    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    . . . . . .
=================================
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionsTest {
    public static void main(String[] args) {
        List<Student> list=new ArrayList<>();
        list.add(new Student("张三",18));
        list.add(new Student("李四",12));
        list.add(new Student("王五",26));
        list.add(new Student("赵六",19));
        //按照年龄升序对student对象进行排序
        Collections.sort(list);
        for (Student student : list) {
            System.out.println(student);
        }
    }
}

运行结果:
在这里插入图片描述
对自定义对象进行比较的前提是要有可以进行排序的属性,比如数字之类的
2. 比较器comparator接口
按照年龄降序排列,代码如下:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class CollectionsTest2 {
    public static void main(String[] args) {
    List<Student> studentList=new ArrayList<>();
        studentList.add(new Student("jack",27));
        studentList.add(new Student("lucy",18));
        studentList.add(new Student("jerry",35));
        studentList.add(new Student("dane",10));
        Collections.sort(studentList, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o2.getAge()-o1.getAge();
            }
        });
        for (Student student : studentList) {
            System.out.println(student);
        }

    }
}

用匿名内部类的方式实现Comparator重写compare方法
运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值