filter(), map() and allMatch()

Isogram
Isogram in Java
import java.util.HashSet;

final class IsogramChecker {

    boolean isIsogram(final String phrase) {
        return phrase.chars()
            .filter(Character::isLetter)
            .map(Character::toLowerCase)
            .allMatch(new HashSet < > ()::add);
    }
}

This approach starts by importing HashSet.

In the isIsogram() method, the chars() method is called on the input String. Each character is passed as a primitive int representing its Unicode codepoint to the filter() method. The filter() passes each codepoint to the IsLetter() method to filter in only letter characters.

Note

Another method that could be used is isAlphabetic(). For the difference between isAlphabetic() and isLetter(), see here.

The surviving codepoints are passed to the map() method which converts the codepoints to lower case.

The lowercased codepoints are passed into the allMatch() method which passes each codepoint into the HashSet's add() method. The add() method returns true if the value is not already in the HashSet and false if the value is already in the HashSet. If add() returns false, then the allMatch() method can know that it will never be true and short-circuit with a result of false. If add() always returns true, then allMatch() will return true.

Finally, the result of allMatch() is returned from the IsIsogram() function.

27th Nov 2024 · Found it useful?