Converting two enums two one Set

Viewed 111

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 got failed as i need to modify the forEach part as well . Can some one please help , how can i modify the forEach part Or how can i use map()/flatmap() function so above line of code can work .

thanks .

1 Answers

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());
Related