How Can I Use Hash Sets in Java to Determine If a String Contains Valid Characters?

I'm writing a lexical analyzer and have never used hash sets. I want to take a string and make sure it's legal. I think I understand how to build the hash set with valid characters but I'm not sure how to compare the string with teh hash set to ensure it contains valid characters. I can't find an example anywhere. Can someone point me to code that would do this?

1

3 Answers

HashSet has the function contains() for this, since it implements the Collection interface.

You cannot compare an entire string to a HashSet<Character>, but you can do it one character at a time:

HashSet<Character> valid = new HashSet<Character>();
valid.add('a');
valid.add('d');
valid.add('f');
boolean allOk = true;
for (char c : "fad".toCharArray()) {
    if (!valid.contains(c)) {
        allOk = false;
        break;
    }
}
System.out.println(allOk);

However, this is not the most efficient way of doing it. A better approach would be to construct a regex with the characters that you need, and call match() on the string:

// Let's say x, y, and z are the valid characters
String regex = "[xyz]*";
if (myString.matches(regex)) {
    System.out.println("All characters in the string are in 'x', 'y', and 'z'");
}

I think you are probably over-thinking this problem. (For instance, spending too much time thinking how to make the lexer "efficient" ...)

The conventional ways to test for valid / invalid characters in a lexer are:

  • use a big switch statement, or

  • perform a sequence of "character class" tests; e.g. using the result of Character.getType(char)

Or better still, use a lexer generator.


Using a HashSet is neither more efficient or more readable than a switch. And the "character class" approach could be a lot more readable than both ... depending on your validation rules.


But if I haven't convinced you, see @blinkenlights' Answer :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest