I have the Enum A, B, C.
In a method, I am given two different Enum and must return the remaining Enum.
Example: I receive A and C I must return B
The solution that I have is to use if elseif else:
private EnumABC findRemaining(EnumABC pEnum1, EnumABC pEnum2){
if((pEnum1 == EnumABC.A || pEnum2 == EnumABC.A)
&& (pEnum1 == EnumABC.B || pEnum2 == EnumABC.B)){
return EnumABC.C;
} else
if((pEnum1 == EnumABC.A || pEnum2 == EnumABC.A)
&& (pEnum1 == EnumABC.C || pEnum2 == EnumABC.C)){
return EnumABC.B;
} else{
return EnumABC.A;
}
}
I was wondering if there was a more readable solution then this.
>Solution :
While Basil’s answer is the most elegant one, this one iterates and is rather readable:
enum EnumABC {
A,B,C;
EnumABC findRemaining(EnumABC other) {
return Arrays.stream(values())
.filter(v -> v!=this&&v!=other)
.findFirst()
.get();
}
}
This is now a method of the enum, so instead of
EnumABC remaining = findRemaining(pEnum1, pEnum2);
you have to call it using
EnumABC remaining = pEnum1.findRemaining(pEnum2);