Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find the remaining Enum

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading