Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to compare strings ignoring case

Short answer

Use equalsIgnoreCase():

void main() {
    IO.println("Hello".equalsIgnoreCase("HELLO"));
    IO.println("Hello".equals("HELLO"));
}

Output:

true
false

Ordering ignoring case

compareToIgnoreCase() compares strings alphabetically, ignoring case:

void main() {
    IO.println("apple".compareToIgnoreCase("BANANA") < 0);
    IO.println("apple".compareTo("BANANA") < 0);
}

Output:

true
false

Sorting 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
true

Common 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
true

Use equalsIgnoreCase() for comparison, and if you need toLowerCase(), pass Locale.ROOT.

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.