Search code examples
javastaticsupplier

Java how to store getters in map


I would like to call a dynamic getter by a given enum. I want to define it in a static map. But I'm not sure how my object will use the method.

I have the Color enum and the object Library.

public enum Color {
   Red,
   Blue,
   Black,
   Green,
   Pink,
   Purple,
   White;
}

public class Library{
  public List<String> getRed();
  public List<String> getBlue();
  public List<String> getBlack();
  .....
}

I want to have a Map ,so when I will have a new Library object by the Type I will call the correct get. For example :

private static Map<Color, Function<......>, Consumer<....>> colorConsumerMap = new HashMap<>();
static {
    colorConsumerMap.put(Color.Red,  Library::getRed);
    colorConsumerMap.put(Color.Blue,  Library::getBlue);
}


Library lib = new Library();
List<String> redList = colorConsumerMap.get(Color.Red).apply(lib)

But this way it doesn't compile. Any suggestions please?


Solution

  • It looks like your Map should be declared as:

    private static Map<Color, Function<Library,List<String>> colorConsumerMap = new HashMap<>()
    

    since your getters return List<String>.