Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating enum of enums

Tags:

java

enums

I have a structure some-thing like

public class EnumTest{
     enum fauna
     {
         Animals, Birds;

         enum Animals
         {
              Tiger("tiger"),
              Lion("lion");

              String name;

              Animals(String name)
              {
                   this.name = name; 
              }
         }

         enum Birds
         {
              Peacock("peacock"),
              owl("Owl");

              String name;

              Birds(String name)
              {
                   this.name = name; 
              }
         }
     }
}

Now I couldn't find a way to iterate over the enum fauna to print the names of enum animals and birds. Is there any way to do it??

like image 983
Aarish Ramesh Avatar asked Dec 20 '25 19:12

Aarish Ramesh


1 Answers

Unfortunately, you can't group enums like this. The enum Birds is distinct from the Birds value inside the fauna enum. The usual way to do it is to add a field which is also an enum:

enum Fauna {
    enum Type { MAMMAL, BIRD }

    TIGER(Type.MAMMAL), 
    LION(Type.MAMMAL), 
    PEACOCK(Type.BIRD), 
    OWL(Type.BIRD);

    private final Type type;

    Fauna(Type type) { this.type = type; }

}

If you only want the animals of a specific type, for example all BIRDs, you will unfortunately have to write a helper method to do that, iterating over all the Fauna values and picking those of the correct type. (Unless you're running Java 8, in which case it's just Stream.of(Fauna.values()).filter(f -> f.type == BIRD).toList() or something similar).

like image 151
gustafc Avatar answered Dec 22 '25 09:12

gustafc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!