1


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!

1 Answers1

1

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);
    }
});
forpas
  • 160,666
  • 10
  • 38
  • 76
  • Or as a one-liner: `coda.sort((a, b) -> a.isManual()? b.isManual()? 0: -1: b.isManual()? +1: Double.compare(a.getAffinity(), b.getAffinity()));` – Holger May 08 '19 at 16:01