Reputation: 209
int a = 10;
int b = 10;
int c = 10;
I am trying to find out if there is alternate way to compare if three ints or anything are equal.
The way i am currently doing is
if( (a == b) && (a == c) && (b == c)){
}
I was wondering if there is an alternate and more concise way to do this.
Upvotes: 7
Views: 29154
Reputation: 1
You can add them into a list, then remove duplicates and compare the size of the actual list minus the unique elements
List elements = Arrays.asList(a,b,c);
List distinct = elements.stream().distinct().toList();
return elements.size() == distinct.size() ? 0 : elements.size() - distinct.size() + 1;
distinct list contains one entry of the duplicate so we have to increment with 1 because we already decreased it.
Or use a HashSet that holds only unique elements
List elements = Arrays.asList(a,b,c);
HashSet<ArrayList> set = new HashSet<>();
set.addAll(elements);
return elements.size() == set.size() ? 0 : elements.size() - set.size() + 1;
Upvotes: 0
Reputation: 1
public static int equal(int a, int b, int c) {
int count = 0;
if (a==b && b==c) {
count = 3;
} else if ((a==b && b!=c) || (a==c && a!=b)) {
count = 2;
}
return count;
}
Upvotes: 0
Reputation: 24156
alternative variant:
int t1 = a-b;
int t2 = c-b;
if ( (t1|t2) == 0 ) // both are equal
Upvotes: 0
Reputation: 13344
If all you need is to know whether three are equal then you can use:
if ((a==b) && (b==c)) {
}
Upvotes: 0
Reputation: 178303
Equality is transitive; you don't need the last comparison b == c
. If a == b
and a == c
, then b == c
.
Try
if ((a == b) && (a == c)){
Upvotes: 35