Search code examples
javaenumscomparison

java comparison of two enums


Given the test code:

@Test
  public void testEnumAreEqual() {
    for (var someEnum : SomeEnum.values()) {
      Assertions.assertTrue(EnumUtils.isValidEnum(OtherEnum.class, someEnum.name()));
    }
    for (var otherEnum : OtherEnum.values()) {
      Assertions.assertTrue(EnumUtils.isValidEnum(SomeEnum.class, otherEnum.name()));
    }
  }

I want to check if two given enums are containing the same values.

Is there maybe a more elegant way to do this?


Solution

  • Build a set of the names:

    Set<String> someEnumNames = 
        Arrays.stream(SomeEnum.values())
            .map(Enum::name)
            .collect(toSet());
    

    Do the same for OtherEnum (consider extracting the above into a method).

    Then:

    assertEquals(someEnumNames, otherEnumNames);