java - 转换两个枚举两个一组

标签 java arrays stream java-stream

我有 2 个实现相同接口(interface)的枚举,如下所示:-

public interface System {
  public String getConfigKey();
}

名为 SystemA 和 SystemB 的两个枚举正在实现此接口(interface)。

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() 函数以便上面的代码行可以工作。

谢谢。

最佳答案

要获取两个枚举的所有值,您需要使用:

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

关于java - 转换两个枚举两个一组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66197192/

相关文章:

java - 使用文本字段和按钮初始化变量

java - 使用 POST 方法在保存之前连接实体

java - 如何使用 Mockito 测试不模拟对象的异步方法?

Javascript - 使用数组传递变量

java - 在 c++/java 中创建 sql 查询?

java - 在java中处理文本文件

c - C 中带有通过 FIFO 管道的指针的结构

python - 替换并打印二维列表python中的字符

node.js - Node 流 promise 错误处理

android - 从 Android 到 PC 上的 VLC 的音频流