Michael
Michael

Reputation: 44210

Idiomatic way to ensure many values are equal

Say I have a list of many primitive variables:

final int a = 3;
final int b = 4;
final int c = 4;
final int d = 4;
final int e = 4;

What's an idiomatic way to make sure they all hold the same value? The obvious way is simply

if (a == b && a == c && a == d && a == e) // ...

But I think this is error prone and hard to read, especially when the variables have proper names, unlike my example.

if (  numCategories == numTypes && numCategories == numColours
   && numCategories == numStyles && numCategories == numPrices) // ...

It would be nice if we could do the comparison like this:

if (a == b == c == d == e)

but obviously a == b resolves to a boolean so we can't compare that to c.

Is there a library function in the JDK or another utility library with maybe a signature somewhat like this?

static boolean areEqual(int... numbers)

then we could use it like so:

if (areEqual(a, b, c, d, e)) //...

I could easily write a function like this myself, but why reinvent the wheel if you don't have to?

Maybe there's another idiomatic way to accomplish this that I'm missing.

Upvotes: 3

Views: 125

Answers (3)

Michael
Michael

Reputation: 44210

I like this approach. There's no auto-boxing and no magic numbers.

As per the documentation, it's also short-circuiting so therefore potentially more efficient than other methods. More importantly, it's very easy to read.

IntStream.of(a, b, c, d).allMatch(x -> x == e);

Credit to saka1029.

Upvotes: 0

Eran
Eran

Reputation: 393946

Using Streams, you can take advantage of some convenient methods to achieve your goal.

You can use Stream's or IntStream's distinct() combined with count() to find the number of unique elements:

For int variables:

if (IntStream.of(a,b,c,d,e).distinct().count() == 1) {

}

For reference type variables:

if (Stream.of(a,b,c,d,e).distinct().count() == 1) {

}

Another way, which is probably less efficient (but I'll keep it here since it's the first thing I thought about) is creating a Stream of all the elements you want to compare and then collecting them into a Set and checking the size of the Set is 1 (since Set doesn't allow duplicates) :

if (IntStream.of(a,b,c,d,e).boxed().collect(Collectors.toSet()).size() == 1) {

}

or

if (Stream.of(a,b,c,d,e).collect(Collectors.toSet()).size() == 1) {

}

for general Objects.

Upvotes: 3

Guy
Guy

Reputation: 50899

A naive option is to build methods that receives all the variables as varargs and compare them one after other. If one of them is different you will get false

public static boolean areEqual(int...nums)
{
    for (int i = 0 ; i < nums.length - 1 ; ++i) {
        if (nums[i] != nums[i + 1]) {
            return false;
        }
    }
    return true;
}

Uses

if (areEqual(a, b, c, d, e))

Upvotes: 3

Related Questions