java comparison of two enums

梦想的初衷 提交于 2019-12-24 23:07:59

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/58538546/simplify-java-enum-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!