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??
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With