filter(), mapToObj() and distinct()

Isogram
Isogram in Java
import java.util.stream.Collectors;

public class IsogramChecker {

    public boolean isIsogram(String input) {
        final var scrubbed = input.chars()
            .filter(Character::isLetter)
            .mapToObj(Character::toLowerCase)
            .collect(Collectors.toList());

        return scrubbed.size() == scrubbed.stream().distinct().count();
    }
}

This approach starts by importing Collectors.

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 mapToObj() method which converts each codepoint to a lowercased codepoint.

The collect() method assembles the lowercased codepoints into a List of codepoint Integers. The size() of the List is compared with the count() of the distinct() letters in the List. If they are equal, then there are no duplicate letters and the comparison returns true from the isIsogram() method. If they are not equal, then there are one or more duplicate letters and the comparison returns false from the isIsogram() method.

27th Nov 2024 · Found it useful?