Collator

The Collator class (part of java.text) is used for locale-sensitive string comparison. It enables accurate sorting and comparison of strings based on the rules of a specific language, making it useful for internationalization.

Key Features:

  • Locale-aware string comparison
  • Supports different comparison strengths (primary, secondary, tertiary)
  • Can sort lists of strings according to local conventions (e.g., in German, “ä” may be treated like “ae”)

Commonly Used Methods

Comparison Strength Levels:

  • Collator.PRIMARY: Ignores case and accents (e.g., “a” == “A” == “á”)
  • Collator.SECONDARY: Considers accents, ignores case
  • Collator.TERTIARY: Considers case and accents

Simple Program

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

public class SimpleCollatorExample {
    public static void main(String[] args) {
        Collator collator = Collator.getInstance(Locale.ENGLISH);

        String str1 = "resume";
        String str2 = "résumé";

        collator.setStrength(Collator.PRIMARY);

        if (collator.compare(str1, str2) == 0) {
            System.out.println("The strings are considered equal.");
        } else {
            System.out.println("The strings are different.");
        }
    }
}
/*
The strings are considered equal.
*/

Problem Statement

Paani and Mahesh are developing a University Student Portal. The portal needs to display student names sorted alphabetically based on German locale, where characters like “ä”, “ö”, “ü” have special sorting rules.

Using the Collator class, implement locale-sensitive sorting for a list of student names.

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

public class GermanNameSorter {
    public static void main(String[] args) {
        String[] studentNames = {
            "Müller",
            "Schneider",
            "Andreas",
            "Zürich",
            "Özil",
            "Ägidius"
        };

        Collator germanCollator = Collator.getInstance(Locale.GERMAN);
        germanCollator.setStrength(Collator.PRIMARY);

        Arrays.sort(studentNames, germanCollator);

        System.out.println("Sorted student names (German Locale):");
        for (String name : studentNames) {
            System.out.println(name);
        }
    }
}
/*
Sorted student names (German Locale):
Ägidius
Andreas
Müller
Özil
Schneider
Zürich
*/

The Collator class is essential for internationalized string comparison and sorting:

  • You need locale-aware string comparison (not just String.compareTo)
  • You want to handle accents, umlauts, and case sensitivity appropriately
  • Building multilingual apps (e.g., student portals, e-commerce, contact lists)
Scroll to Top