shamika Dharmasiri shamika Dharmasiri - 1 year ago 75
Java Question

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 with 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 their anyway to achieve this, other than writing a raw object sorting method?

Thanks in advance.

Answer Source

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

public int compare(Zone z1, Zone z2){
      return z1.getZoneName().compareTo(z2.getZoneName());
      return z1.getZoneName().toLowerCase().compareTo(z2.getZoneName().toLowerCase());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download