Sid Sid - 3 months ago 18
Java Question

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

I am trying to check if a string contains all the letters of the alphabet. I created an

ArrayList
which contains the whole alphabet. I converted the string to char array and I'm iterating through the character array, and for every character present in the
ArrayList
I'm removing an element from it. And in the end, I'm trying to check if the
Arraylist
is empty to see if all elements have been removed. That would indicate the string contains all the letters of the alphabet.

Unfortunately, the code is throwing
IndexOutOfBoundsException
error inside the if condition where I'm removing elements from the arraylist

List<Character> alphabets = new ArrayList<Character>();

alphabets.add('a');
alphabets.add('b');
alphabets.add('c');
alphabets.add('d');
alphabets.add('e');
alphabets.add('f');
alphabets.add('g');
alphabets.add('h');
alphabets.add('i');
alphabets.add('j');
alphabets.add('k');
alphabets.add('l');
alphabets.add('m');
alphabets.add('n');
alphabets.add('o');
alphabets.add('p');
alphabets.add('q');
alphabets.add('r');
alphabets.add('s');
alphabets.add('t');
alphabets.add('u');
alphabets.add('v');
alphabets.add('w');
alphabets.add('x');
alphabets.add('y');
alphabets.add('z');

// This is the string- I've just put a random example
String str = "a dog is running crazily on the ground who doesn't care about the world";

//Remove all the spaces
str = str.replace(" ", "");

// Convert the string to character array
char[] strChar = str.toCharArray();

for (int i = 0; i < strChar.length; i++) {

char inp = strChar[i];

if (alphabets.contains(inp)) {
alphabets.remove(inp);
}
}

if (alphabets.isEmpty())
System.out.println("String contains all alphabets");
else
System.out.println("String DOESN'T contains all alphabets");

Answer

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<>();
String s = /* Your lowercase string */;
s.length > 25 && s.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