Is There a Simpler Way to Check Multiple Values Against One Value in an If-Statement

Is there a simpler way to check multiple values against one value in an if-statement?

Unfortunately there is no such construct in Java.

It this kind of comparison is frequent in your code, you can implement a small function that will perform the check for you:

public boolean oneOfEquals(int a, int b, int expected) {
return (a == expected) || (b == expected);
}

Then you could use it like this:

if(oneOfEquals(a, b, 0)) {
// ...
}

If you don't want to restrict yourselft to integers, you can make the above function generic:

public <T> boolean oneOfEquals(T a, T b, T expected) {
return a.equals(expected) || b.equals(expected);
}

Note that in this case Java runtime will perform automatic boxing and unboxing for primitive types (like int), which is a performance loss.

If statement, compare one variable to multiple

You use || to do boolean OR comparison. The single bar, | is used for bit operations. Your current syntax is incorrect.

if(value ==1 || value==2 || value ==3)

Of course, it might be better to do a range check here like so:

if(value>=1 && value<=3)

Not sure what you're trying to do though.

If the OR comparison makes more sense for you here, you should define some constants for these values, or consider an enumerated type. The literals 1, 2, and 3 have no meaning to other developers.

How to test multiple variables for equality against a single value?

You misunderstand how boolean expressions work; they don't work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for:

if x == 1 or y == 1 or z == 1:

x and y are otherwise evaluated on their own (False if 0, True otherwise).

You can shorten that using a containment test against a tuple:

if 1 in (x, y, z):

or better still:

if 1 in {x, y, z}:

using a set to take advantage of the constant-cost membership test (i.e. in takes a fixed amount of time whatever the left-hand operand is).

Explanation

When you use or, python sees each side of the operator as separate expressions. The expression x or y == 1 is treated as first a boolean test for x, then if that is False, the expression y == 1 is tested.

This is due to operator precedence. The or operator has a lower precedence than the == test, so the latter is evaluated first.

However, even if this were not the case, and the expression x or y or z == 1 was actually interpreted as (x or y or z) == 1 instead, this would still not do what you expect it to do.

x or y or z would evaluate to the first argument that is 'truthy', e.g. not False, numeric 0 or empty (see boolean expressions for details on what Python considers false in a boolean context).

So for the values x = 2; y = 1; z = 0, x or y or z would resolve to 2, because that is the first true-like value in the arguments. Then 2 == 1 would be False, even though y == 1 would be True.

The same would apply to the inverse; testing multiple values against a single variable; x == 1 or 2 or 3 would fail for the same reasons. Use x == 1 or x == 2 or x == 3 or x in {1, 2, 3}.

Best way to format multiple 'or' conditions in an if statement

I use this kind of pattern often. It's very compact:

// Define a constant in your class. Use a HashSet for performance
private static final Set<Integer> values = new HashSet<Integer>(Arrays.asList(12, 16, 19));

// In your method:
if (values.contains(x)) {
...
}

A HashSet is used here to give good look-up performance - even very large hash sets are able to execute contains() extremely quickly.

If performance is not important, you can code the gist of it into one line:

if (Arrays.asList(12, 16, 19).contains(x))

but know that it will create a new ArrayList every time it executes.

Compare to multiple values in an if statement

Use the in operator

if num in a : 

as in

def test(num): 
a = [1, 2, 3]
if num in a :
return True
else :
return False

a work around would be (as suggested by Padraic)

 def test(num): 
a = [1, 2, 3]
return num in a

This would work because, The in operator compares if the LHS is present in the RHS and returns a boolean value respectively.

Also this is possible

test = lambda x:  num in [1, 2, 3]

That is all in a single line!

Simplifying greater than IF statements with multiple ANDs based on the same value

I'd write something like that:

if (max($a, $b, $c, $d, $e) == $a) {
....
}

if statements matching multiple values

How about:

if (new[] {1, 2}.Contains(value))

It's a hack though :)

Or if you don't mind creating your own extension method, you can create the following:

public static bool In<T>(this T obj, params T[] args)
{
return args.Contains(obj);
}

And you can use it like this:

if (1.In(1, 2))

:)



Related Topics



Leave a reply



Submit