0

I would like to create a lambda replacement for this current code:

Map<String,Consumer> executionMap = new HashMap<>();
executionMap.put("operation1", str -> this.getEntity().setBooleanCondition(Boolean.parseBoolean(str))

For cases where I don't need to do transform the argument I have this:

executionMap.put("operation2", this.getEntity()::setAStringValue);

I am annoyed because I can figure out how to make the boolean case as elegant.

Additional example of being annoyed:

executionMap.put("operation3", str -> {
   this.getEntity().setAStringValueA(str);
   this.getEntity().setAStringValueB(str);
});

For this second case I tried :

executionMap.put("operation3", 
   this.getEntity()::setAStringValueA.andThen(this.getEntity()::setAStringValueB);

But this got a compilation error.

I feel like the answer(s) are obvious but I am not seeing the path.

Naman
  • 27,789
  • 26
  • 218
  • 353
Pat
  • 5,761
  • 5
  • 34
  • 50
  • 4
    *"I would like to create a lambda replacement"* By that, do you actually mean that you want to replace the *lambda expression* with a *method reference*? In both examples, that's what you are doing, but you never actually say so. If that's what you meant, please edit the question and clarify by explicitly saying so. If that's not what you meant, please edit the question and clarify what it is you actually meant. – Andreas Jul 02 '20 at 20:49
  • 4
    Please edit the question and explain what is not *elegant* about a lambda expression, because I think that `str -> { stmt1; stmt2; }` is at least as elegant as `stmt1.andThen(stmt2)`. I actually think the intent is clearer, using a lambda expression block, in this case. – Andreas Jul 02 '20 at 20:53
  • 1
    You are annoyed because you are forced to use the right tool for the job? – Holger Jul 03 '20 at 08:22

1 Answers1

1

Your operation3 is pretty straightforward.

executionMap
    .put("operation3", ((Consumer<String>)this.getEntity()::setAStringValueA)
    .andThen(this.getEntity()::setAStringValueB));
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
Alanpatchi
  • 1,177
  • 10
  • 20