Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort objects in Java with case sensitive String key

I have a requirement to sort objects(Zone) with their names(Zone Name : String) considering the case. I tried this with Java Comparator interface.

class NameComparator implements Comparator<Zone> {
    public int compare(Zone z1, Zone z2) {
        return z1.getZoneName().compareTo(z2.getZoneName());
   }
}

But this Comparator only sort lexicographically.

Ex : Required order for the zone names.

['Zone AAa3','Zone aaa3','Zone BBB7','Zone BBb7','Zone bbb7']

Current Output :

['Zone AAa3','Zone BBB7','Zone BBb7','Zone aaa3','Zone bbb7']

Is there any way to achieve this, other than writing a raw object sorting method?

like image 504
shamika Dharmasiri Avatar asked Jun 06 '16 03:06

shamika Dharmasiri


2 Answers

There is a pre-defined comparator for case-insensitive sorting. You can use it with a Zone by extracting a sort key.

Comparator<Zone> byName = Comparator
    .comparing(Zone::getZoneName, String.CASE_INSENSITIVE_ORDER)
    .thenComparing(Zone::getZoneName);
like image 200
erickson Avatar answered Oct 01 '22 03:10

erickson


Tweak the logic, convert both name to lower case or upper case and then compare.

public int compare(Zone z1, Zone z2){
  if(z1.getZoneName().toLowerCase().equals(z2.getZoneName().toLowerCase()))
      return z1.getZoneName().compareTo(z2.getZoneName());
  else
      return z1.getZoneName().toLowerCase().compareTo(z2.getZoneName().toLowerCase());
}

Using lambda -

Comparator<Zone> byName = (z1, z2)->{
    if(z1.getZoneName().toLowerCase().equals(z2.getZoneName().toLowerCase()))
       return z1.getZoneName().compareTo(z2.getZoneName());
    else
       return z1.getZoneName().toLowerCase().compareTo(z2.getZoneName().toLowerCase());
};
like image 31
Subhrajyoti Majumder Avatar answered Oct 01 '22 03:10

Subhrajyoti Majumder