适用于多种条件的Collections.sort [英] Collections.sort for multiple conditions

查看:73
本文介绍了适用于多种条件的Collections.sort的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要排序的对象列表.但是我有三个不同的条件.这就是为什么我有以下代码:

I have a list of objects which I want to sort. But I have three different conditions. That is why I have this code:

Collections.sort(myList, new Comparator<MyObject>() {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        // my code
    }
});

三遍.首先将条件为 x 的所有元素排序到列表的底部.然后第二次将条件为 y 的所有元素排序到底部,并再次对条件为 z 的元素进行排序.

Three times. First sorting all elements with condition x to the bottom of the list. Then a second time sorting all elements with condition y to the bottom and again for condition z.

现在我想知道如何在一个比较方法中组合多个条件.因此,我不必三遍.

Now I wonder how I could combine multiple conditions in one compare-method. So I don't have to do this three times.

编辑:要进一步了解条件.我想将所有具有条件 x 的对象排序到列表的底部.如果元素满足 y 的条件,则该元素应甚至低于 x ,并且对 z 使用类似的元素.

To be more clear about the conditions. I want to sort all objects that have the criteria x to the bottom of the list. If an element fulfills criteria y it should be even below x and the same applies analog for z.

推荐答案

您可以使用Java Streams.使用

You can use Java Streams. This is also used when using Collection.sort():

myList.sort(Comparator.comparing(MyObject::getAttributeX)
    .thenComparing(i -> i.getSomething().getSubValue())
    .thenComparing((a, b) -> a.getInt() - b.getInt()));

如果使用的版本低于Java 8,则必须自己在 Comparator 中实现排序逻辑或使用外部库:

If you are using a lower version than Java 8 you have to implement the sort logic yourself in a Comparator or use an external library:

Collections.sort(myList, new Comparator<MyObject>() {
    @Override
    public int compare(MyObject a, MyObject b) {
        int cmp0 = a.getAttributeX().compareTo(b.getAttributeX());
        if (cmp0 != 0) {
            return cmp0;
        }
        int cmp1 = a.getSomething().getSubValue().compareTo(b.getSomething().getSubValue());
        if (cmp1 != 0) {
            return cmp1;
        }
        return a.getInt() - b.getInt();
    }
});

这篇关于适用于多种条件的Collections.sort的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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