A cleaner if statement with multiple comparisons

if-statement, java

Solution

Set<String> stuff = new HashSet<String>();
stuff.add("x");
stuff.add("y");
stuff.add("z");
if(stuff.contains(a)) {
    //stuff
}

If this is a tight loop you can use a static Set.

static Set<String> stuff;
static {
    stuff = new HashSet<String>();
    stuff.add("x");
    stuff.add("y");
    stuff.add("z");
}

//Somewhere else in the cosmos

if(stuff.contains(a)) {
    //stuff
}

And if you want to be extra sure nothing is getting modified while you're not looking.

Set<String> test = Collections.unmodifiableSet(new HashSet<String>() {
        {
            add("x");
            add("y");
            add("z");
        }
    });

If you just want to get some logic in there for a handful of hard coded conditions then one of the switch or if statement with newlines solutions might be better. But if you have a lot of conditions then it might be good to separate your configuration from logic.

Problem

The following statement just looks very messy when you have a lot of terms: ``` if(a.equals("x") || a.equals("y") || a.equals("z") || Any number of terms...... ) //Do something ``` Is there a cleaner way of performing the same action, I would like my code to be as readable as possible. NOTE: x, y and z are just placeholders for any string of any length. There could be 20 string terms here of variable length in if condition each being OR'd together

Original source