4

This is a bit of a specific question, but I want to know how to make a HashMap of functions that are obtained in parameters, like so:

//All functions will take in string and return void
public HashMap<String,Function> functions = new HashMap<String,Function>();
public void addMethod(String name, Function func){
   functions.put(name, func);
}
public void useMethod(String name, String input){
   functions[name](input);
}

How would I do this correctly?

Isaac Krementsov
  • 646
  • 2
  • 12
  • 28

2 Answers2

3

You can use a Consumer<String>.

First, change your HashMap to:

public HashMap<String,Consumer<String>> functions = new HashMap<>();

then your addMethod to:

public void addMethod(String name, Consumer<String> func){
    functions.put(name, func);
}

then you useMethod to:

public void useMethod(String name, String input){
    functions.get(name).accept(input);
}
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • 2
    It'd be better to design the code oriented to interfaces. By this, define the attribute as `private Map> functions = ...`. – Luiggi Mendoza Jun 03 '18 at 19:07
2

All functions will take in string and return void

In this situation, you can use a Consumer<String> interface and create a factory as follows:

public class ConsumerFactory {

    private static final Map<String, Consumer<String>> consumers = new HashMap<>();

    public static Consumer<String> getConsumer(String key) {
        if (key != null && consumers.containsKey(key)) {
            return consumers.get(key);
        }
        throw new NoSuchElementException(key);
    }

    public static Consumer<String> addConsumer(String key, Consumer<String> value) {
        return consumers.put(key, value);
    }
}

ConsumerFactory.addConsumer("print", System.out::println);
ConsumerFactory.getConsumer("print").accept("Hello");
Oleksandr Pyrohov
  • 14,685
  • 6
  • 61
  • 90