Dmitry_08 Dmitry_08 -4 years ago 79
Java Question

How can I find if an element of one enum contrains in the other?

Good afternoon.

I would like to ask the question about Java enum: if there are two enums

enum Elements_1 {aaa, bbb, ccc};


and

enum Elements_2 {ccc, ddd, eee};


How can we figure out if an element of one contains in the other?

Thank You.

Answer Source

This should work if checking the names of your enumeration is what you need:

List<String> enumA = Arrays.stream(Elements_1.values()).map(Enum::name).collect(Collectors.toList());
List<String> enumB = Arrays.stream(Elements_2.values()).map(Enum::name).collect(Collectors.toList());
enumA.retainAll(enumB);

enumA will show you the intersection between both Enums.


Or without streams:

List<String> enumA = new ArrayList<>();
for (Enum constant : Elements_1.values())
    enumA.add(constant.name());

List<String> enumB = new ArrayList<>();
for (Enum constant : Elements_2.values())
    enumB.add(constant.name());

enumA.retainAll(enumB);

If you want to check for only one element at runtime, I would recommend you store enumA as a static in your Enum, then implement a simple method to check the intersection with contains().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download