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
- Start with "a" and "A"
- Do this Compare at English primary strength
- Result Equal
Apply it to a real problem
- Start with Catalog names café and CAFE
- Do this Compare using English primary collation
- Result Same sort group
Advertisements
Run the example
Save as Main.java and run java Main.java with JDK 21.
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);
}
}
true true