5

I've just spent almost hour debugging a List<String> in my code which was being sorted wrong by my Comparator.

Turns out that string.compareTo(string2) is case-sensitive. Meaning that all Capital letters come before the lowercase letters. e.g. "Z" comes before "d".

Is there any better way of comparing 2 Strings inside a Comparatorand sorting them alphabetically ascending without them being case sensitive other then string.toLowerCase().compareTo(string2.toLowerCase()); ?

Edit: There's a possibility of any accented letter appearing in my String like for example: ä, ö, ü, é, è, etc.

D.Mendes
  • 159
  • 1
  • 11
  • 1
    use `.equalsIgnoreCase()` – Sofo Gial Nov 16 '18 at 09:40
  • 1
    @SofoGial That checks equality only, not which is bigger or smaller which `copareTo` does and which is required to establish sorting order. – Pshemo Nov 16 '18 at 09:41
  • Do you use accented letters (or umlauts etc)? – DodgyCodeException Nov 16 '18 at 09:47
  • @DodgyCodeException yes I do, sry for forgetting to Mention that. There's the possibility of accented letters existing like for example: ä, ö, ü, è, é, etc... – D.Mendes Nov 16 '18 at 09:51
  • @D.Mendes While accented characters are handled by ignoring the case, it will assume a != ä but ä == Ä – Peter Lawrey Nov 16 '18 at 09:53
  • Related (perhaps even duplicate): https://stackoverflow.com/questions/2220400/how-do-i-make-my-string-comparison-case-insensitive and for further information https://stackoverflow.com/questions/8885885/difference-between-collator-locale-sensitive-and-compareto-lexicographically – Hulk Nov 16 '18 at 10:13

4 Answers4

13

You have two options provided in String itself:

As a tip: your first stop should be the Javadoc, not post a question on Stack Overflow: the Javadoc is extensive and will usually provide a quick answer.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
6

Use String.CASE_INSENSITIVE_ORDER.compare

talex
  • 17,973
  • 3
  • 29
  • 66
1

use compareToIgnoreCase() method

https://docs.oracle.com/javase/9/docs/api/java/lang/String.html#compareToIgnoreCase-java.lang.String-

e.g78
  • 667
  • 4
  • 8
  • https://docs.oracle.com/javase/9/docs/api/java/lang/String.html#compareToIgnoreCase-java.lang.String- – e.g78 Nov 16 '18 at 09:44
0

compareToIgnoreCase

The String Api has a second compare to function that does a compare while ignoring case.

string1.compareToIgnoreCase(string2);
Community
  • 1
  • 1
Dinomaster
  • 256
  • 1
  • 6