Mirco Ianese
Mirco Ianese

Reputation: 25

How to Sort Objects in ArrayList by more than one rule


I have a Java ArrayList containing some objects of type ObjType.

Let's say the object has two fields:
- A boolean field isManual()
- A double value getAffinity()

I'm trying to order this ArrayList based on more than one criteria:
-First all the objects with isManual=true on the same order that they already have in the ArrayList
-Then I want all the objects with isManual=false ordered by the getAffinityValue (from the lowest to the greatest)

I've come up with this code, which is not working (it seems it's randomly sorting):

Collections.sort(coda, new Comparator<ObjType>() {

            public int compare(ObjType a, ObjType b) {
                boolean b1=a.isManual();
                boolean b2=b.isManual();
                if(b1 && b2) {
                    if (a.getAffinity() < b.getAffinity()) return 1;
                    if (a.getAffinity() > b.getAffinity()) return -1;
                    return 0;
                }
                if (b1) return -1;
                if (b2) return 1;
                if (a.getAffinity() < b.getAffinity()) return 1;
                if (a.getAffinity() > b.getAffinity()) return -1;
                return 0;
            }
}

Any suggestions? Thanks a lot!

Upvotes: 1

Views: 104

Answers (1)

forpas
forpas

Reputation: 164069

First all the objects with isManual=true on the same order that they already have in the ArrayList

Then in the case where both objects have isManual == true you should not return anything other than 0.

Then I want all the objects with isManual=false ordered by the getAffinityValue (from the lowest to the greatest)

Then these lines:

if (a.getAffinity() < b.getAffinity()) return 1;
if (a.getAffinity() > b.getAffinity()) return -1; 

should return the opposite values that they do return.
So try this:

Collections.sort(coda, new Comparator<ObjType>() {
    public int compare(ObjType a, ObjType b) {
        boolean b1=a.isManual();
        boolean b2=b.isManual();

        if(b1 && b2) return 0;
        if (b1) return -1;
        if (b2) return 1;

        Double affinity1 = a.getAffinity();
        Double affinity2 = b.getAffinity();
        return affinity1.compareTo(affinity2);
    }
});

Upvotes: 1

Related Questions