Sort and compare text with an explicit locale in Java

Choose a locale and comparison strength when case and accents should be treated as equivalent for a lookup. A zero comparison signals a match.

A simple example

Compare at English primary strength

  1. Start with "a" and "A"
  2. Do this Compare at English primary strength
  3. Result Equal
Case differences do not affect this comparison.

Apply it to a real problem

  1. Start with Catalog names café and CAFE
  2. Do this Compare using English primary collation
  3. Result Same sort group
A catalog can treat case and accents as secondary differences under this rule.
Advertisements

Run the example

Save as Main.java and run java Main.java with JDK 21.

Main.java
import java.text.Collator;
import java.util.Locale;

public class Main {
    public static void main(String[] args) throws Exception {
        var names = Collator.getInstance(Locale.ENGLISH);
        names.setStrength(Collator.PRIMARY);
        System.out.println(names.compare("café", "CAFE") == 0);
        System.out.println(names.compare("apple", "pear") < 0);
    }
}
Output
true
true

Official Java documentation