使用多个键对Java对象进行排序 [英] Sorting Java objects using multiple keys

查看:109
本文介绍了使用多个键对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);
    }
});

我经常这样做,但这个解决方案闻不到。它不能很好地扩展,并且很容易搞砸。当然必须有一个更好的方法来使用多个键对Ducks进行排序!有没有人知道更好的解决方案?

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 removed unnecessary else branches

推荐答案

Java 8解决方案:

Java 8 solution:

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

对于lambdas,方法引用和默认方法来说万岁!太糟糕了,我们必须定义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,因此你必须指定第一个的参数类型两个lambdas。 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对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆