Visit the pangram exercise on Exercism to read the full instructions and download the exercise files.
Dig Deeper
filter(), distinct() and count()
filter() and distinct() with count()
public class PangramChecker {
private final static int LETTERS_IN_ALPHABET = 26;
public boolean isPangram(String input) {
return input.toLowerCase().chars()
.filter(Character::isLetter)
.distinct()
.count() == LETTERS_IN_ALPHABET;
}
}
This approach starts be defining a private final static value for all 26 letters in the English alphabet.
It is private because it does not need to be directly accessed from outside the class,
and it is final because its value does not need to be changed once it is set.
It is static because it doesn’t need to differ between object instantiations, so it can belong to the class itself.
The input String is lowercased and chained into the chars() method.
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.
Another method that could be used is [`isAlphabetic()`](https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isAlphabetic-int-).
For the difference between `isAlphabetic()` and `isLetter()`, see [here](https://www.baeldung.com/java-character-isletter-isalphabetic).
The the count() of the distinct() surviving codepoints are compared with the number of letters expected,
which for the English alphabet is 26.
This works as long as the only letters in the input are in the English alphabet.
If the input was missing a but had α, then the distinct letters would be 26 but it would not be a Pangram for English.
containsAll()
containsAll()
import java.util.Arrays;
public class PangramChecker {
public boolean isPangram(String input) {
return Arrays.asList(input.toLowerCase().split(""))
.containsAll(Arrays.asList("abcdefghijklmnopqrstuvwxyz".split("")));
}
}
This approach starts by importing from packages for what is needed.
The input String is lowercased and chained into the split() method to create an array of Strings.
The enclosing Arrays.asList() method converts the String array into a List of Strings.
The `chars()` and `toCharArray()` methods won't work for `Arrays.asList()` because they produce primitive `int`s or `char`s
respectively.
For `Arrays.asList()` to work as desired, it must take an array of reference types.
The `split()` method is used here because it returns an array of `String`s, and `String` is a reference type.
The List of input character Strings is chained to the containsAll() method.
A String List of the English lowercase letters is passed to containsAll().
If all letters in the English alphabet are contained in the input, then containsAll() returns true,
otherwise it returns false.
Because the condition is for all English letters being in the input, the input does not need to have non-letters filtered out.
Source: Exercism java/pangram