How to compare strings ignoring case
Short answer
Use equalsIgnoreCase():
void main() {
IO.println("Hello".equalsIgnoreCase("HELLO"));
IO.println("Hello".equals("HELLO"));
}Output:
true
falseOrdering ignoring case
compareToIgnoreCase() compares strings alphabetically, ignoring case:
void main() {
IO.println("apple".compareToIgnoreCase("BANANA") < 0);
IO.println("apple".compareTo("BANANA") < 0);
}Output:
true
falseSorting a list
The ready-made comparator String.CASE_INSENSITIVE_ORDER sorts strings ignoring case:
void main() {
var names = new ArrayList<>(List.of("oleg", "Anna", "boris"));
names.sort(String.CASE_INSENSITIVE_ORDER);
IO.println(names);
}Output:
[Anna, boris, oleg]Searching a list
contains() is case-sensitive, so to search without case use a stream with equalsIgnoreCase():
void main() {
var roles = List.of("Admin", "Editor");
IO.println(roles.contains("admin"));
IO.println(roles.stream().anyMatch(role -> role.equalsIgnoreCase("admin")));
}Output:
false
trueCommon mistake
Lowercasing with toLowerCase() without arguments depends on the system language. In the Turkish locale "TITLE".toLowerCase() gives "tıtle" with a dotless i, and the comparison breaks:
void main() {
var turkish = Locale.of("tr");
IO.println("TITLE".toLowerCase(turkish).equals("title"));
IO.println("TITLE".equalsIgnoreCase("title"));
}Output:
false
trueUse equalsIgnoreCase() for comparison, and if you need toLowerCase(), pass Locale.ROOT.
Functions used in this recipe
- String.equalsIgnoreCase() — Compares two strings ignoring letter case.
- String.compareTo() — Compares two strings in dictionary (lexicographic) order.
- String.toLowerCase() — Returns a copy of the string with all letters in lower case.
- String.equals() — Compares the contents of two strings.