当前位置: 首页 > 工具软件 > comparator > 使用案例 >

比较器:Comparator的用法

左丘昕
2023-12-01

在使用优先队列时,我们可以自定义比较器,构造方法如下,这是在做leetcode.502题时遇到的,有思路,但是不会实现,现在用这篇文章记录一下:

       // 构造方法
    public PriorityQueue(Comparator<? super E> comparator) {
        this(DEFAULT_INITIAL_CAPACITY, comparator);
    }
    // 使用
    Queue<Integer> queue = new PriorityQueue<>((x, y) -> y - x);

一、概述

Comparable和Comparator在java中都是用于来比较数据大小。实现Comparable接口需要重写compareTo方法,实现Comparator方法需要重写compare方法。 这两个方法返回值都是int类型,根据返回值来判断比较对象的大小,从而实现排序

二、用法

        Comparable需要实现,重写compareto方法

    public int compareTo(T o);

从小到大:this.getXXX - o.getXXX()

从大到小:o.getXXX - this.getXXX

Comparetor接口,重写compare()方法

    public static int compare(double d1, double d2) {}

从小到大:return d1 - d2;

从大到小:  return d2 - d1;

再加一种可直接排序的方法,我们使用User对象来进行验证

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Integer age;
    private Double money;
    private String name;
}
public class CompareterTest {
    public static void main(String[] args) {
        List<User> list = new ArrayList<>();
        list.add(new User(1, 1.0, "c"));
        list.add(new User(1, 2.0, "a"));
        list.add(new User(1, 2.0, "b"));
        list.add(new User(3, 2.0, "a"));
        list.add(new User(3, 1.0, "c"));
        list.add(new User(3, 3.0, "b"));
        list.add(new User(2, 1.0, "b"));
        System.out.println(list);
        // 在集合工具类排序时可使用thenComparing方法进行多字段排序
        Collections.sort(list, Comparator.comparingInt((User::getAge))
                .thenComparing(User::getMoney)
                .thenComparing(User::getName));
        Collections.sort(list, (a, b) -> {
            // 按年龄倒叙
            return b.getAge() - a.getAge();
        });
        System.out.println(list);
    }
}

也可在对象中实现Comparetor接口的compare方法进行自定义排序

 类似资料: