Collator Locale Aware Sorting
Compare strings the way users expect with a locale Collator; strength levels decide whether accents and case count as a difference when sorting.
Code
import java.text.Collator;
import java.util.List;
import java.util.Locale;
public class DirectorySort {
public static void main(String[] args) {
List<String> names = List.of("Abel", "Ábel", "Zoe", "Zoë");
// String.compareTo 按码点比较:带重音的名字被甩到列表末尾
System.out.println("code point order: " + names.stream().sorted().toList());
Collator collator = Collator.getInstance(Locale.FRENCH);
// PRIMARY:只比基础字母,重音与大小写都视为相同
collator.setStrength(Collator.PRIMARY);
System.out.println("primary Abel vs Ábel: " + collator.compare("Abel", "Ábel"));
System.out.println("primary Zoe vs Zoë: " + collator.compare("Zoe", "Zoë"));
System.out.println("primary sort: " + names.stream().sorted(collator).toList());
// SECONDARY:基础字母相同后再分辨重音,大小写仍然不参与
collator.setStrength(Collator.SECONDARY);
System.out.println("secondary Abel vs Ábel: " + collator.compare("Abel", "Ábel"));
System.out.println("secondary Abel vs abel: " + collator.compare("Abel", "abel"));
}
}Inside the snippet
The snippet is organized around the class DirectorySort and the function main.
Data flows through a stream pipeline where each stage returns a new view rather than mutating.
Putting it to use
Each run prints the 6 labeled blocks code point order:, primary Abel vs Ábel:, primary Zoe vs Zoë:, primary sort:, secondary Abel vs Ábel:, secondary Abel vs abel: in source order.
Core lines
List<String> names = List.of("Abel", "Ábel", "Zoe", "Zoë");
Collator collator = Collator.getInstance(Locale.FRENCH);
collator.setStrength(Collator.SECONDARY);
Interactive Tools for This Topic
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.Number FormatterFormat numbers with thousands grouping, fixed decimals, custom separators, and an optional prefix or suffix.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Collator Locale Aware Sorting print when run?
- The script runs standalone; its 6 labeled outputs include `code point order:`, `primary Abel vs Ábel:`, `primary Zoe vs Zoë:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.