两个枚举的java比较 [英] java comparison of two enums

查看:91
本文介绍了两个枚举的java比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出测试代码:

@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?

推荐答案

构建一组名称:

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

OtherEnum 执行相同操作(请考虑提取

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

然后:

assertEquals(someEnumNames, otherEnumNames);

这篇关于两个枚举的java比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆