Calling a list of methods

user1288455 :

I have a scenario where, depending on the value of one variable, I'll set different other variables as null. Something like:

switch (object.getControllerVariable()){
case "A":
    object.setB(null);
    object.setC(null);
    break;
case "B":
    object.setA(null);
    object.setC(null);
    break;
case "C":
    object.setA(null);
    object.setC(null);
    break;
}

The real life scenario is a little lenghtier than that, and likely to grow in the future. What I wanted to do would be create a create a list with all the setters, inside the switch just remove the one that shouldn't be executed, and at the and call them all with the same value. Can this be accomplished?

Sweeper :

You can store all those setters into a list.

What I would do is to store them in a HashMap<String, Consumer<TypeOfObject>>:

HashMap<String, Consumer<TypeOfObject>> setters = new HashMap<>();
setters.put("A", x -> x.setA(null));
setters.put("B", x -> x.setB(null));
setters.put("C", x -> x.setC(null));

And then you can do something like:

setters.entrySet().stream()
    .filter(x -> !x.getKey().equals(object.getControllerVariable()))
    .forEach(x -> x.getValue().accept(object));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=99318&siteId=1