A cleaner if statement with multiple comparisons

Alternatively, if you are using Java 7+ you can use strings in switch/case. For example (I extracted this from an Oracle doc and modified)

         switch (str) {

             case "x":
             case "y":
             case "z":
                 //do action
                 break;
             default:
              throw new IllegalArgumentException("argument not matched "+str);

    }

Here is the link


Use a regular expression

If (a.matches("[xyz]")){
    // matches either "x", "y", or "z"

or, for longer strings,

If (a.matches("one|two|three")){
    // matches either "one", "two" or "three"

But this is computationally expensive, but probably not much worse than instantiating a set etc. But it's the clearest way I can think of.

But in the end, the nicest way is probably to leave things as they are, with an adjustment to the formatting:

if (a.equals("x") || 
    a.equals("y") || 
    a.equals("z")
    ){

There is then absolutely no ambiguity in what the code is doing and so your code will be easier to maintain. If performance matters, you can even put the most likely occurrences towards the top of the list.


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.


What do you think looks "unclean" about it?

If you have a bunch of complicated boolean logic, you might separate the different parts of it into individual boolean variables and refer to them in the if statement.

Or you could create a function that takes your 'a' variable and returns a boolean. You'd just be hiding your logic in the method, but it would clean up your if statement.