I have 2 enums which implements same interface like following:
public interface System {
public String getConfigKey();
}
Two enums named SystemA
and SystemB
are implementing this 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;
}
}
I wanted to apply getConfigFunction commonly like this : -
Set<String> configKeys = Stream.<System>of(SystemA.values(),
SystemB.values()).forEach(config -> config.getConfigKey()).collect(toSet());
But it's throwing Compile Time Error as the formed stream is of type : Config [] . So i tried with following modification : -
Set<String> configKeys = Stream.<System []>of(SystemA.values(),
SystemB.values()).forEach(config -> config.getConfigKey()).collect(toSet());
But this also failed as I need to modify the forEach
part as well.
Can someone please help, how can I modify the forEach
part? Or how can I use map()
/flatmap()
function so above line of code can work ?
To get all values of both enums then you need to use:
Set<String> configKeys = Stream.of(SystemA.values(), SystemB.values())
.flatMap(Arrays::stream)
.map(System::getConfigKey)
.collect(toSet());