将两个枚举类型转换为一个集合

3

我有两个实现同一个接口的枚举,如下所示:

public interface System {
  public String getConfigKey();
}

两个枚举类型SystemA和SystemB实现了这个接口。

public enum SystemA implements System {
   ABC_CONFIG("ABC");

   private SystemA(String configKey) {
    this.configKey = configKey;
   }

   private String configKey;

   public String getConfigKey() {
      return configKey;
   }
}

public enum SystemB implements System {
   DEF_CONFIG("DEF");

   private SystemB(String configKey) {
      this.configKey = configKey;
   }

   private String configKey;

   public String getConfigKey() {
     return configKey;
   }
}

我想要像这样通用地应用getConfigFunction:-
Set<String> configKeys = Stream.<System>of(SystemA.values(), 
                SystemB.values()).forEach(config -> config.getConfigKey()).collect(toSet());

但是它抛出了编译时错误,因为生成的流是类型为:Config []。

所以我尝试进行以下修改:

Set<String> configKeys = Stream.<System []>of(SystemA.values(), 
                    SystemB.values()).forEach(config -> config.getConfigKey()).collect(toSet());

但这也失败了,因为我需要修改forEach部分。 请问有人可以帮忙吗?我该如何修改forEach部分?或者我应该如何使用map()/flatmap()函数,使得上述代码行可以正常工作。
谢谢。

你把“Config”改成了“System”,现在代码片段和错误信息不再匹配。 - luk2302
抱歉,我已经适当修改了问题。你可以再看一下吗? - Shivanshu
你需要使用.map(config -> config.getConfigKey())而不是forEach,因为forEach是一个终止操作。 - Youcef LAIDANI
.map(config -> config.getConfigKey()) 不起作用,因为形成的流是 System [] * 类型,而不是 System* 类型。而 getConfigKey() 函数是针对 System* 的,而不是 System [] 的。 - Shivanshu
1个回答

3

如果要获取两个枚举的全部值,则需要使用:

Set<String> configKeys = Stream.of(SystemA.values(), SystemB.values())
        .flatMap(Arrays::stream)
        .map(System::getConfigKey)
        .collect(toSet());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接