An idiomatic way to ensure that many values ​​are equal

Let's 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 have the same meaning? The obvious way is to simply

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

      

But I think this is a bug prone and hard to read, especially when the variables have their own 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

allows a boolean, so we can't compare that with c

.

Is there a library function in the JDK or other utility library, perhaps such a signature?

static boolean areEqual(int... numbers)

      

then we could use it like this:

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

      

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

Perhaps there is another idiomatic way to achieve this that I am missing.

+3


source to share


3 answers


By using Stream

s, you can take advantage of some convenient ways to achieve your goal.

You can use Stream

or IntStream

distinct()

in combination with count()

to find the number of unique items:

For int

variables:

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

}

      

For reference variable types:

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 this is the first thing I thought about) creates Stream

all the elements you want to compare and then collect them in Set

and check the size Set

is 1 (since it 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 common Object

s.

+3


source


The naive option is to create methods that take all the variables as varargs and compare them one by one. If one of them is different, you will receivefalse

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;
}

      



Using

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

      

+3


source


I like this approach. There are no automatic boxing and magic numbers.

According to the documentation , this is also short-circuiting, so potentially more efficient than other methods. More importantly, it is very easy to read.

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

      

Credit saka1029 .

0


source







All Articles