INSIGHTS
Software Development

Understanding Anagrams in Java and Their Real-World Relevance

In this article
  1. Choose the input rule before the algorithm
  2. A complete Java implementation
  3. Why frequency counting works
  4. Punctuation and spaces are explicit choices
  5. Unicode normalization is necessary but not sufficient
  6. Test cases that expose mistakes
  7. What this exercise teaches

Two strings are anagrams under a chosen set of rules when their normalized characters occur with the same frequencies. For example, “listen” and “silent” are anagrams when letter order is ignored. A program must still decide whether spaces, punctuation, case, accented characters and Unicode combining marks count. Those rules are part of the task, not implementation details to leave implicit.

Choose the input rule before the algorithm

The example below ignores punctuation and spaces, uses Unicode NFC normalization, and folds ordinary case using Locale.ROOT. It then compares counts of Unicode code points, not UTF-16 code units. That is useful for a teaching example, but it is not a universal multilingual collation or linguistic equivalence algorithm.

For a password or authentication check, do not normalize or discard characters this way; that problem requires different semantics and should not be implemented with an anagram tutorial.

A complete Java implementation

import java.text.Normalizer;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class AnagramCheck {
    static Map<Integer, Integer> counts(String input) {
        String normalized = Normalizer.normalize(input, Normalizer.Form.NFC)
                .toLowerCase(Locale.ROOT);
        Map<Integer, Integer> result = new HashMap<>();
        normalized.codePoints()
                .filter(Character::isLetterOrDigit)
                .forEach(cp -> result.merge(cp, 1, Integer::sum));
        return result;
    }
    static boolean isAnagram(String a, String b) {
        return counts(a).equals(counts(b));
    }
    public static void main(String[] args) {
        System.out.println(isAnagram("Listen", "Silent"));
        System.out.println(isAnagram("Dormitory", "Dirty room!!"));
        System.out.println(isAnagram("apple", "paper"));
    }
}

Compile the file as AnagramCheck.java and run it with javac AnagramCheck.java followed by java AnagramCheck. The expected lines are true, true and false. The Map holds code-point counts, so the order of the original input cannot affect the comparison.

Why frequency counting works

If two normalized strings have the same multiset of code points, then every included character appears the same number of times. Comparing frequency maps directly implements that property. The average running time is linear in the number of code points under ordinary hash-map assumptions; sorting is another valid approach with approximately O(n log n) time for a comparison-based sort.

Punctuation and spaces are explicit choices

A word-game rule may ignore punctuation; a case-sensitive identifier comparison must not. Here the filter retains only letters and digits. If a problem requires spaces to count, remove that filter and count every code point. State the rule in the function name or documentation so callers do not mistake one version for a universal definition of anagram.

Unicode normalization is necessary but not sufficient

NFC combines canonically equivalent sequences where applicable, such as a precomposed accented letter and its decomposed representation. It does not automatically equate every visually similar glyph, every language-specific case fold or all compatibility forms. Consult Oracle’s Unicode Normalizer documentation if multilingual requirements are important.

Test cases that expose mistakes

Check an empty pair, repeated letters, same-length non-anagrams, mixed case, spaces, a decomposed accented character and a supplementary Unicode code point. The meaningful result for two empty inputs depends on the product rule; this function treats them as anagrams because both frequency maps are empty. Reject null inputs or document their preconditions before using the function in a public API.

What this exercise teaches

The lasting skill is translating a plain-English equality rule into a normalized representation and comparing it with tests. The exact technique also applies to inventory comparisons and character-frequency tasks, but search indexing, cryptography and human-language matching require stronger domain-specific models than this exercise alone provides.

Filed under Software Development