Simplifying If-conditions

Viewed 118

Is there a way to simplify:

if(a == b || a == o || a == j || a ==....)
{
    ...
}

I thought I could do something like

if( a == (b || o || j || ...))
{
     ...
}

But that turned out to be incorrect syntax

2 Answers

create a method to take the value of a and a varargs of the other elements, then you can stream over the elements and check if any is equal to the value of a.

an example:

public boolean anyMatch(int a, int... values){
      return Arrays.stream(values).anyMatch(e -> e == a);
}

then you can call it like so:

if(anyMatch(a, o, j, b)){ ... };

I suppose your variables are integers.

List<Integer> values = Arrays.asList(b, o, j);
if (values.contains(a)){
...
}
Related