我有 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/