Localized Dates, Collation and Unicode Normalization in Java
Presenting dates in the user's language and calendar, parsing what users type, first day of the week, sorting strings correctly with Collator (strength, decomposition, collation keys, custom rules, locale extensions) and making equal text equal with java.text.Normalizer.
kvi5hnuCode Sprout team member12 min readOn this page
This article handles two everyday tasks that go wrong as soon as a program leaves its home country. The first is showing dates and times in a way users recognize. The second is comparing and sorting text. String.compareTo compares UTF-16 code units, which puts Zulu before able and Ångström after everything else, and it treats two visually identical strings as different if they are encoded differently. The tools are DateTimeFormatter (covered in detail in article 70), java.text.Collator and java.text.Normalizer.
Dates for an international audience
Four things vary by locale when you show a date or time:
- the names of months and weekdays,
- the order of day, month and year, and the separators,
- the calendar system (Gregorian, Buddhist, Japanese imperial, and others),
- the time zone and the way it is named.
Localized formatters handle the first three from the locale; the fourth comes from the value you format. Pick a FormatStyle and a locale:
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
.withLocale(userLocale);
String text = f.format(appointment); // appointment is a ZonedDateTime
ofLocalizedDate, ofLocalizedTime and ofLocalizedDateTime(dateStyle, timeStyle) cover the combinations. The demo below shows all four styles for the Apollo 11 launch in New York (en-US) and the same instant in Berlin (de-DE). Two details stand out. The German LONG style prints MEZ (Central European standard time) for July, which is historically correct, because West Germany had no daylight saving time in 1969; the zone database knows. And the LONG and FULL time styles print a zone name, so they work only with values that have a zone, such as ZonedDateTime.
To use a different calendar, put it in the locale and use localizedBy (Java 10), which also changes the formatter's chronology: th-TH-u-ca-buddhist prints the year 1969 as 2512.
Parsing what users type
The localized formatters parse exactly the text they produce, and that is stricter than people expect:
- Since JDK 20, US times contain a narrow no-break space (U+202F) before AM/PM, so
9:32 AMtyped with an ordinary space does not matchofLocalizedTime(SHORT). 9:32AMand9:32 amfail too: the space is required and AM/PM is case-sensitive.- With a
SMARTresolver (the default for localized formatters), the impossible date11/31/25silently becomes November 30.
For user input, build a forgiving formatter with DateTimeFormatterBuilder: parseLenient() (since JDK 23, lenient mode also lets any space character match any other) and parseCaseInsensitive(). Better still, use date and time pickers in the user interface and avoid free-form typing altogether. If you must validate, use ResolverStyle.STRICT with a pattern that uses uuuu.
Names of months and days, standalone forms
Month.getDisplayName(style, locale) and DayOfWeek.getDisplayName(style, locale) give names for calendars, drop-down menus and column headers. The TextStyle values come in pairs:
| Style | Inside a date | Standalone |
|---|---|---|
FULL / FULL_STANDALONE | January | January |
SHORT / SHORT_STANDALONE | Jan | Jan |
NARROW / NARROW_STANDALONE | J | J |
In English the two forms are the same, but many languages inflect month names inside a date. In Finnish, January is tammikuuta in a date and tammikuu on its own; in Russian it is января and январь. Use the _STANDALONE styles for headings, and in patterns use LLLL (standalone month) instead of MMMM when the month appears alone.
The first day of the week
A calendar grid starts on Sunday in the US, on Monday in most of Europe, and on Saturday in many Middle Eastern countries. WeekFields.of(locale) gives the first day of the week and the minimal number of days in the first week of the year (which defines week numbers). The Unicode extension fw overrides it: en-US-u-fw-mon keeps US formats but starts the week on Monday.
Collation: sorting text for people
Sorting with String.compareTo (or List.sort(null)) uses code unit values:
America, Zulu, able, zebra, Ångström
All capital letters come before lower-case ones, and letters outside ASCII come last. An English reader expects case to be ignored, and Å to sort with A. A Swedish reader expects Å after Z, because it is a separate letter at the end of the Swedish alphabet:
| Locale | Order |
|---|---|
compareTo | America, Zulu, able, zebra, Ångström |
| English | able, America, Ångström, zebra, Zulu |
| Swedish | able, America, zebra, Zulu, Ångström |
A Collator encapsulates the sorting rules of a locale. It implements Comparator<Object>, so you can pass it straight to sort:
Collator coll = Collator.getInstance(locale);
words.sort(coll);
German puts Öl between Ofen and Ozean, treating Ö as a variant of O. Because rules differ by language, you choose the collator by the reader's locale, not by the language of the data.
Strength
Collators distinguish three levels of difference, and the strength decides which levels count:

| Strength | Angstrom vs Ångström | Able vs able | able vs abel |
|---|---|---|---|
PRIMARY | equal | equal | different |
SECONDARY | different | equal | different |
TERTIARY (default) | different | different | different |
IDENTICAL | different | different | different |
The defaults are fine for sorting, since a sort uses the weaker levels only to break ties. Lower strengths are useful for searching and duplicate detection: with PRIMARY strength, a search for eclair also finds éclair and Eclair. Note that the levels are a property of the language: in Swedish, å versus a is a primary difference, not a secondary one.
Decomposition
Unicode often has more than one way to write the same text. Å can be the single code point U+00C5 or A (U+0041) followed by a combining ring above (U+030A). The ligature ffi (U+FB03) stands for ffi, and ™ (U+2122) is in some sense TM. A collator's decomposition mode decides how hard it tries to see through these differences:
| Mode | Å vs A + ring | ™ vs TM | ffi vs ffi |
|---|---|---|---|
NO_DECOMPOSITION (default) | different* | different | different |
CANONICAL_DECOMPOSITION | equal | different | different |
FULL_DECOMPOSITION | equal | equal | equal |
* The demo compares at IDENTICAL strength. The JDK's rule-based collators have the common precomposed accented letters built into their tables, so at the default TERTIARY strength, Å and A + ring already compare equal in many cases even without decomposition. Turn on CANONICAL_DECOMPOSITION when text may contain combining sequences in arbitrary order, and FULL_DECOMPOSITION for compatibility characters such as ligatures and full-width letters. More decomposition is slower.
The JDK also lets you request collator settings through locale extensions (verified on JDK 25): co chooses a collation type (sv-u-co-trad for traditional Swedish, which does not distinguish v and w), ks the strength (level1 to level3, identic) and kk the normalization (true for canonical decomposition). Collator.getInstance(Locale.forLanguageTag("en-u-ks-level1-kk-true")) returns a primary-strength collator with canonical decomposition.
Collation keys
Comparing with a collator is more work than compareTo: each comparison may decompose and look up both strings in rule tables. When the same strings are compared many times, as in sorting a large list or searching a big index, precompute a CollationKey for each:
CollationKey key = coll.getCollationKey(text);
key.compareTo(otherKey); // fast, byte comparison
key.getSourceString(); // the original text
Keys from the same collator compare in the same order as the collator would, and toByteArray() gives a byte form that you can store and compare elsewhere.
Custom rules
The collators returned for most locales are RuleBasedCollator instances. getRules() returns their rule string, and you can append your own. Traditional Spanish treated ch as a separate letter between c and d:
RuleBasedCollator base = (RuleBasedCollator) Collator.getInstance(Locale.ENGLISH);
var oldSpanish = new RuleBasedCollator(base.getRules() + "& c < ch");
// cama, cuna, chico, dedo
The syntax uses < for a primary difference, ; for secondary, , for tertiary, = for equality and & to reset the position. For anything beyond small tweaks, the ICU4J library offers the full Unicode Collation Algorithm with current CLDR data.
Normalization
Collation solves comparison inside a sort, but often you need equal strings to be equal: as map keys, in database columns, in file names, in passwords. Two Ångström strings, one composed and one decomposed, look the same on screen, but equals returns false and their hashCodes differ. macOS file systems, for example, have historically stored names in decomposed form, while text typed on most keyboards is composed.
java.text.Normalizer converts text to one of the four Unicode normalization forms (UAX #15):
| Form | Name | Effect on Ångström ffi ™ ½ |
|---|---|---|
NFD | canonical decomposition | A + ring, o + diaeresis; ffi, ™, ½ kept |
NFC | canonical decomposition, then composition | Å, ö as single code points; ffi, ™, ½ kept |
NFKD | compatibility decomposition | accents split, and ffi → ffi, ™ → TM, ½ → 1⁄2 |
NFKC | compatibility decomposition, then composition | accents composed, ffi → ffi, ™ → TM, ½ → 1⁄2 |
String nfc = Normalizer.normalize(input, Normalizer.Form.NFC);
boolean done = Normalizer.isNormalized(input, Normalizer.Form.NFC);
Guidelines:
- NFC is the W3C recommendation for text on the web and the right default for storage and exchange. Normalize at the boundary, when data enters the system.
- NFKC is useful for identifiers and search, where
java(full-width) should matchjava. It loses information (the™becomes plainTM), so do not apply it to text you will show unchanged. - NFD followed by removing combining marks (
replaceAll("\\p{M}", "")) is the usual trick to strip accents for search slugs:Crème BrûléebecomesCreme Brulee. It is lossy and wrong for languages where the marks change the letter, so use it only for matching, never for display.
The program
The demo formats dates in several styles and calendars, tries to parse typical user input, shows standalone month names and week starts, sorts with several collators, checks strength and decomposition, uses collation keys and a custom rule, and normalizes a string into all four forms (shown as code points).
import java.text.*;
import java.time.*;
import java.time.format.*;
import java.time.temporal.WeekFields;
import java.util.*;
public class Solution {
public static void main(String[] args) throws ParseException {
ZonedDateTime launch = ZonedDateTime.of(1969, 7, 16, 9, 32, 0, 0, ZoneId.of("America/New_York"));
ZonedDateTime berlin = launch.withZoneSameInstant(ZoneId.of("Europe/Berlin"));
System.out.println("== Localized date and time ==");
for (FormatStyle st : FormatStyle.values()) {
System.out.printf("%-6s %-42s | %s%n", st,
v(DateTimeFormatter.ofLocalizedDateTime(st).withLocale(Locale.US).format(launch)),
v(DateTimeFormatter.ofLocalizedDateTime(st).withLocale(Locale.GERMANY).format(berlin)));
}
System.out.println("mixed styles: " + v(DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.SHORT).withLocale(Locale.UK).format(launch)));
System.out.println("Thai Buddhist calendar: " + DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG)
.localizedBy(Locale.forLanguageTag("th-TH-u-ca-buddhist")).format(launch));
System.out.println("\n== Parsing localized text ==");
DateTimeFormatter usShortTime = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withLocale(Locale.US);
for (String in : List.of("9:32\u202fAM", "9:32 AM", "9:32AM", "9:32 am")) {
try {
System.out.println("\"" + v(in) + "\" -> " + LocalTime.parse(in, usShortTime));
} catch (DateTimeParseException e) {
System.out.println("\"" + v(in) + "\" -> fails at index " + e.getErrorIndex());
}
}
DateTimeFormatter loose = new DateTimeFormatterBuilder().parseLenient().parseCaseInsensitive()
.append(usShortTime).toFormatter(Locale.US);
for (String in : List.of("9:32 AM", "9:32 am")) {
try {
System.out.println("lenient+case-insensitive \"" + in + "\" -> " + LocalTime.parse(in, loose));
} catch (DateTimeParseException e) {
System.out.println("lenient+case-insensitive \"" + in + "\" -> fails");
}
}
DateTimeFormatter usShortDate = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).withLocale(Locale.US);
System.out.println("11/31/25 -> " + LocalDate.parse("11/31/25", usShortDate));
System.out.println("\n== Month names, standalone vs in a date ==");
Locale fi = Locale.forLanguageTag("fi");
Locale ru = Locale.forLanguageTag("ru");
System.out.println("fi: " + Month.JANUARY.getDisplayName(TextStyle.FULL, fi) + " / "
+ Month.JANUARY.getDisplayName(TextStyle.FULL_STANDALONE, fi));
System.out.println("ru: " + Month.JANUARY.getDisplayName(TextStyle.FULL, ru) + " / "
+ Month.JANUARY.getDisplayName(TextStyle.FULL_STANDALONE, ru));
System.out.println("ru in a date: " + DateTimeFormatter.ofPattern("d MMMM", ru).format(launch)
+ ", standalone LLLL: " + DateTimeFormatter.ofPattern("LLLL", ru).format(launch));
System.out.println("\n== First day of the week ==");
for (String tag : List.of("en-US", "de-DE", "ar-EG", "en-GB", "en-US-u-fw-mon")) {
WeekFields wf = WeekFields.of(Locale.forLanguageTag(tag));
System.out.printf("%-15s first=%-9s minDaysInFirstWeek=%d%n", tag,
wf.getFirstDayOfWeek(), wf.getMinimalDaysInFirstWeek());
}
System.out.println("\n== String.compareTo versus Collator ==");
List<String> words = new ArrayList<>(List.of("Zulu", "able", "Ångström", "zebra", "America"));
words.sort(null);
System.out.println("compareTo : " + words);
words.sort(Collator.getInstance(Locale.ENGLISH));
System.out.println("en : " + words);
words.sort(Collator.getInstance(Locale.forLanguageTag("sv")));
System.out.println("sv : " + words);
List<String> german = new ArrayList<>(List.of("Ofen", "Öl", "Ozean", "Ober"));
german.sort(Collator.getInstance(Locale.GERMAN));
System.out.println("de : " + german);
List<String> vw = new ArrayList<>(List.of("wc", "vb", "va", "wa"));
vw.sort(Collator.getInstance(Locale.forLanguageTag("sv")));
System.out.println("sv : " + vw);
vw.sort(Collator.getInstance(Locale.forLanguageTag("sv-u-co-trad")));
System.out.println("sv co-trad: " + vw);
System.out.println("\n== Strength ==");
Collator en = Collator.getInstance(Locale.ENGLISH);
String[][] pairs = {{"Angstrom", "Ångström"}, {"Able", "able"}, {"able", "abel"}};
String[] names = {"PRIMARY", "SECONDARY", "TERTIARY", "IDENTICAL"};
for (int s = Collator.PRIMARY; s <= Collator.IDENTICAL; s++) {
en.setStrength(s);
StringBuilder sb = new StringBuilder(String.format("%-9s", names[s]));
for (String[] p : pairs)
sb.append(" ").append(p[0]).append(en.compare(p[0], p[1]) == 0 ? " = " : " ≠ ").append(p[1]);
System.out.println(sb);
}
Collator viaTag = Collator.getInstance(Locale.forLanguageTag("en-u-ks-level1-kk-true"));
System.out.println("en-u-ks-level1-kk-true: strength PRIMARY? " + (viaTag.getStrength() == Collator.PRIMARY)
+ ", canonical decomposition? " + (viaTag.getDecomposition() == Collator.CANONICAL_DECOMPOSITION));
System.out.println("default strength TERTIARY? " + (Collator.getInstance(Locale.ENGLISH).getStrength() == Collator.TERTIARY));
System.out.println("\n== Decomposition ==");
String composed = "Å";
String decomposed = "Å";
String[] modes = {"NO_DECOMPOSITION", "CANONICAL_DECOMPOSITION", "FULL_DECOMPOSITION"};
Collator c = Collator.getInstance(Locale.ENGLISH);
System.out.println("default decomposition: " + modes[c.getDecomposition()]);
c.setStrength(Collator.IDENTICAL);
for (int m = Collator.NO_DECOMPOSITION; m <= Collator.FULL_DECOMPOSITION; m++) {
c.setDecomposition(m);
System.out.printf("%-24s Å vs A+ring: %s ™ vs TM: %s ffi vs ffi: %s%n", modes[m],
eq(c, composed, decomposed), eq(c, "™", "TM"), eq(c, "ffi", "ffi"));
}
System.out.println("\n== Collation keys ==");
Collator keyed = Collator.getInstance(Locale.ENGLISH);
keyed.setStrength(Collator.PRIMARY);
List<CollationKey> keys = new ArrayList<>();
for (String w : List.of("zebra", "Able", "éclair", "eclair", "America"))
keys.add(keyed.getCollationKey(w));
Collections.sort(keys);
StringJoiner sj = new StringJoiner(", ");
for (CollationKey k : keys) sj.add(k.getSourceString());
System.out.println("sorted by key: " + sj);
System.out.println("éclair key equals eclair key: "
+ (keyed.getCollationKey("éclair").compareTo(keyed.getCollationKey("eclair")) == 0));
System.out.println("\n== Custom rules ==");
RuleBasedCollator base = (RuleBasedCollator) Collator.getInstance(Locale.ENGLISH);
RuleBasedCollator custom = new RuleBasedCollator(base.getRules() + "& c < ch");
List<String> spanishOld = new ArrayList<>(List.of("chico", "cuna", "dedo", "cama"));
spanishOld.sort(custom);
System.out.println("ch as a separate letter after c: " + spanishOld);
System.out.println("\n== Normalizer ==");
String name = "Ångström";
for (Normalizer.Form f : Normalizer.Form.values()) {
String n = Normalizer.normalize(name + " ffi ™ ½", f);
System.out.printf("%-4s length=%2d %s%n", f, n.length(), codes(n.substring(0, n.indexOf(' '))));
}
System.out.println("equals before NFC: " + composed.equals(decomposed)
+ ", after: " + Normalizer.normalize(composed, Normalizer.Form.NFC)
.equals(Normalizer.normalize(decomposed, Normalizer.Form.NFC)));
System.out.println("isNormalized(A+ring, NFC): " + Normalizer.isNormalized(decomposed, Normalizer.Form.NFC));
String stripped = Normalizer.normalize("Crème Brûlée", Normalizer.Form.NFD)
.replaceAll("\\p{M}", "");
System.out.println("accents removed: " + stripped);
System.out.println("NFKC of full-width Java: "
+ Normalizer.normalize("Java", Normalizer.Form.NFKC));
}
static String eq(Collator c, String a, String b) {
return c.compare(a, b) == 0 ? "=" : "≠";
}
static String codes(String s) {
StringJoiner sj = new StringJoiner(" ");
s.codePoints().forEach(cp -> sj.add(String.format("%04X", cp)));
return sj.toString();
}
static String v(String s) {
return s.replace("\u202f", "<NNBSP>").replace("\u00a0", "<NBSP>");
}
}
== Localized date and time ==
FULL Wednesday, July 16, 1969, 9:32:00<NNBSP>AM Eastern Daylight Time | Mittwoch, 16. Juli 1969, 14:32:00 Mitteleuropäische Normalzeit
LONG July 16, 1969, 9:32:00<NNBSP>AM EDT | 16. Juli 1969, 14:32:00 MEZ
MEDIUM Jul 16, 1969, 9:32:00<NNBSP>AM | 16.07.1969, 14:32:00
SHORT 7/16/69, 9:32<NNBSP>AM | 16.07.69, 14:32
mixed styles: Wednesday, 16 July 1969, 09:32
Thai Buddhist calendar: 16 กรกฎาคม 2512
== Parsing localized text ==
"9:32<NNBSP>AM" -> 09:32
"9:32 AM" -> fails at index 4
"9:32AM" -> fails at index 4
"9:32 am" -> fails at index 4
lenient+case-insensitive "9:32 AM" -> 09:32
lenient+case-insensitive "9:32 am" -> 09:32
11/31/25 -> 2025-11-30
== Month names, standalone vs in a date ==
fi: tammikuuta / tammikuu
ru: января / январь
ru in a date: 16 июля, standalone LLLL: июль
== First day of the week ==
en-US first=SUNDAY minDaysInFirstWeek=1
de-DE first=MONDAY minDaysInFirstWeek=4
ar-EG first=SATURDAY minDaysInFirstWeek=1
en-GB first=MONDAY minDaysInFirstWeek=4
en-US-u-fw-mon first=MONDAY minDaysInFirstWeek=1
== String.compareTo versus Collator ==
compareTo : [America, Zulu, able, zebra, Ångström]
en : [able, America, Ångström, zebra, Zulu]
sv : [able, America, zebra, Zulu, Ångström]
de : [Ober, Ofen, Öl, Ozean]
sv : [va, vb, wa, wc]
sv co-trad: [va, wa, vb, wc]
== Strength ==
PRIMARY Angstrom = Ångström Able = able able ≠ abel
SECONDARY Angstrom ≠ Ångström Able = able able ≠ abel
TERTIARY Angstrom ≠ Ångström Able ≠ able able ≠ abel
IDENTICAL Angstrom ≠ Ångström Able ≠ able able ≠ abel
en-u-ks-level1-kk-true: strength PRIMARY? true, canonical decomposition? true
default strength TERTIARY? true
== Decomposition ==
default decomposition: NO_DECOMPOSITION
NO_DECOMPOSITION Å vs A+ring: ≠ ™ vs TM: ≠ ffi vs ffi: ≠
CANONICAL_DECOMPOSITION Å vs A+ring: = ™ vs TM: ≠ ffi vs ffi: ≠
FULL_DECOMPOSITION Å vs A+ring: = ™ vs TM: = ffi vs ffi: =
== Collation keys ==
sorted by key: Able, America, éclair, eclair, zebra
éclair key equals eclair key: true
== Custom rules ==
ch as a separate letter after c: [cama, cuna, chico, dedo]
== Normalizer ==
NFD length=16 0041 030A 006E 0067 0073 0074 0072 006F 0308 006D
NFC length=14 00C5 006E 0067 0073 0074 0072 00F6 006D
NFKD length=21 0041 030A 006E 0067 0073 0074 0072 006F 0308 006D
NFKC length=19 00C5 006E 0067 0073 0074 0072 00F6 006D
equals before NFC: false, after: true
isNormalized(A+ring, NFC): false
accents removed: Creme Brulee
NFKC of full-width Java: Java
Common questions
How do I sort names in a TreeMap or with streams correctly?
Pass a collator: new TreeMap<>(Collator.getInstance(locale)) or .sorted(Collator.getInstance(locale)). For records, Comparator.comparing(Person::name, collator). A collator is a Comparator<Object>, which fits wherever a Comparator<String> is expected through the comparing overload.
Is Collator thread-safe?
The JDK's RuleBasedCollator implementation is synchronized internally, but because it's also mutable (setStrength), the safe practice is one instance per thread, or call clone(), especially in heavily concurrent code where synchronization becomes a bottleneck.
How do I search case- and accent-insensitively?
For comparing whole strings, use a collator with PRIMARY strength. For substring search, normalize both strings (Normalizer.normalize(s, Form.NFD)), remove combining marks with replaceAll("\\p{M}", ""), and lower-case with Locale.ROOT. Note that this "accent folding" is wrong for languages where accented letters are distinct, such as Swedish.
Should I normalize all input? Normalizing to NFC at input boundaries (form fields, file names, imported data) is a good default, and avoids invisible duplicates. Use NFKC for identifiers and user names, where compatibility characters such as full-width letters should match their plain forms.
Why doesn't "ß".toUpperCase() give ß back when I lower-case it again?
"ß".toUpperCase(Locale.ROOT) is "SS", which lower-cases to "ss". Case mapping isn't always reversible and can change string length. equalsIgnoreCase compares character by character, so "ß".equalsIgnoreCase("SS") is false. When such matches matter, compare with a German collator at SECONDARY strength, or use full case folding from ICU4J.
API reference
| Method | Purpose |
|---|---|
DateTimeFormatter.ofLocalizedDate/Time/DateTime(...), withLocale, localizedBy | localized dates and times |
DateTimeFormatterBuilder.parseLenient(), parseCaseInsensitive() | forgiving parsing |
Month/DayOfWeek.getDisplayName(TextStyle, Locale) | names, with _STANDALONE variants |
WeekFields.of(locale).getFirstDayOfWeek(), getMinimalDaysInFirstWeek() | week rules |
Collator.getInstance([locale]) | locale-specific comparator |
compare(String, String), equals(String, String) | comparison |
setStrength(PRIMARY/SECONDARY/TERTIARY/IDENTICAL) | which differences count |
setDecomposition(NO/CANONICAL/FULL_DECOMPOSITION) | normalization before comparing |
getCollationKey(String), CollationKey.compareTo, toByteArray | precomputed keys |
RuleBasedCollator(String rules), getRules() | custom ordering |
Normalizer.normalize(CharSequence, Form), isNormalized | NFC, NFD, NFKC, NFKD |
Summary
- Show dates with localized formatters in the user's locale; put calendar and week preferences into the locale (
-u-ca-,-u-fw-). - Localized formatters parse only their own exact output. Use lenient, case-insensitive builders or, better, date pickers for user input.
- Use
_STANDALONEtext styles andLLLLfor month names that appear on their own. - Never sort user-visible text with
compareTo. UseCollator.getInstance(readerLocale). - Strength selects which differences count (base letters, accents, case); lower strengths are good for searching.
- Default decomposition is
NO_DECOMPOSITION; enable canonical or full decomposition when input may contain combining sequences or compatibility characters. - Use
CollationKeywhen comparing the same strings many times. - Normalize text to NFC when it enters the system so that equal-looking strings are
equals; use NFKC for identifiers and search keys.
Practice Questions
1. A list of customer names is sorted with Collections.sort(names). What will Swedish and English users notice?
compareTo orders by UTF-16 code units, so all upper-case names come before all lower-case ones, and names starting with accented letters (Ångström, Øberg, Élise) end up after Z. English users expect case-insensitive order with accents treated as variants; Swedish users expect Å, Ä, Ö as separate letters after Z. Sort with Collator.getInstance(userLocale) instead.
2. How do you implement a search where "resume" finds "Résumé" and "RESUME" but not "resumes"?
Use a collator with PRIMARY strength: coll.setStrength(Collator.PRIMARY), then test coll.equals(query, candidate), or compare collation keys. Primary strength ignores accents and case but still sees the extra s. For prefix or substring search, compare collation keys of the candidates' substrings or use a full-text search engine with a matching analyzer.
3. Two strings print identically, but s1.equals(s2) is false and the HashMap lookup fails. What is the likely cause and fix?
They are probably in different normalization forms, for example a precomposed é (U+00E9) in one and e + combining acute (U+0065 U+0301) in the other. Normalize both, ideally when the data enters the system, with Normalizer.normalize(s, Normalizer.Form.NFC), and use the normalized strings as keys.
4. A month drop-down shows "января, февраля, ..." to Russian users. What went wrong?
The code used TextStyle.FULL (or the pattern MMMM), which gives the form used inside a date, in the genitive case. For a month shown on its own, use TextStyle.FULL_STANDALONE (or the pattern LLLL), which gives январь, февраль, ....
5. Why is NFKC appropriate for normalizing usernames but not for normalizing article text?
NFKC folds compatibility characters into their plain equivalents: full-width letters, ligatures, superscripts, ™. For usernames this prevents look-alike registrations (john and john become the same). For article text, the folding destroys meaningful formatting, such as x² becoming x2 or ½ becoming 1⁄2, so text meant for display should be normalized to NFC, which only unifies canonically equivalent sequences.
Previous: Number Formats in Java: NumberFormat, Compact Numbers, DecimalFormat and Currencies
Next: MessageFormat and ChoiceFormat in Java: Placeholders, Plurals and Choices
Related reading
- Number Formats in Java: NumberFormat, Compact Numbers, DecimalFormat and Currencies
- Locales in Java: Language Tags, Default Locales and Display Names
- Formatting and Parsing Dates in Java, and Converting Legacy Date and Calendar
- LocalTime, ZonedDateTime and Daylight Saving Time in Java
- LocalDate, Period and Temporal Adjusters in Java

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.