Collections.sort for multiple conditions

progNewbie :

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
    }
});

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.

Edit: 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.

Samuel Philipp :

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()));

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();
    }
});

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=110970&siteId=1