本文介绍了使用多个键对 Java 对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组 Duck 对象,我想使用多个键对它们进行排序.

I've got a collection of Duck objects and I'd like to sort them using multiple keys.

class Duck {
    DuckAge age; //implements Comparable
    DuckWeight weight; //implements Comparable
    String name;
}
List<Duck> ducks = Pond.getDucks();

例如.我想对它们进行主要按体重排序,然后按年龄排序.如果两只鸭子具有完全相同的体重和完全相同的年龄,那么让我们使用它们的名字作为第三键来区分它们.我可能会做这样的事情:

eg. I want to sort them primarily by their weights, and secondarily by their age. If two ducks have the exact same weight and the exact same age, then let's differentiate them using their names as a tertiary key. I might do something like this:

Collections.sort(ducks, new Comparator<Duck>(){
    @Override
    public int compare(Duck d1, Duck d2){
        int weightCmp = d1.weight.compareTo(d2.weight);
        if (weightCmp != 0) {
            return weightCmp;
        }
        int ageCmp = d1.age.compareTo(d2.age);
        if (ageCmp != 0) {
            return ageCmp;
        }
        return d1.name.compareTo(d2.name);
    }
});

嗯,我经常这样做,但这个解决方案闻起来不太对.它不能很好地扩展,而且很容易搞砸.肯定有更好的方法来使用多个键对鸭子进行排序!有人知道更好的解决方案吗?

Well I do this quite frequently, but this solution doesn't smell right. It doesn't scale well, and it's easy to mess up. Surely there must be a better way of sorting Ducks using multiple keys! Does anybody know of a better solution?

EDIT 删除了不必要的else 分支

EDIT removed unnecessary else branches

推荐答案

Java 8 解决方案:

Java 8 solution:

Comparator<Duck> cmp = Comparator.comparing(Duck::getWeight)
    .thenComparing(Duck::getAge)
    .thenComparing(Duck::getName);

Lambda、方法引用和默认方法万岁:)!太糟糕了,我们必须定义 getter,或者使用显式 lambdas,如下所示:

Hooray for lambdas, method references, and default methods:)! Too bad we have to define getters, or use explicit lambdas, like so:

Comparator<Duck> cmp = Comparator
    .comparing((Duck duck)-> duck.weight)
    .thenComparing((Duck duck)-> duck.age)
    .thenComparing(duck-> duck.name);

类型推断不适用于隐式 lambda,因此您必须指定前两个 lambda 的参数类型.Brian Goetz 的回答中的更多详细信息.

Type inference won't work with implicit lambdas, so you have to specify the argument type of the first two lambdas. More details in this answer by Brian Goetz.

这篇关于使用多个键对 Java 对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 11:36