How to check if a string contains all the letters of the alphabet?

Published on Author Code Father

All these solutions seem to do a lot of work for a relatively simple check, especially given Java 8’s stream API:

/* Your lowercase string */.chars().
    filter(i -> i >= 'a' && i <= 'z').distinct().count() == 26;

Edit: For speed

If you want to end the string iteration as soon as the entire alphabet is found, then you can keep track with a HashSet internally:

Set<Integer> chars = new HashSet<>();
/* Your lowercase string */.chars()
    .filter(i -> i >= 'a' && i <= 'z') //only alphabet
    .filter(chars::add) //add to our tracking set if we reach this point
    .filter(i -> chars.size() == 26) //filter the 26th letter found
    .findAny().isPresent(); //if the 26th is found, return

This way, the stream will cease as soon as the Set is filled with the 26 required characters

Comments

comments