Pat
Pat

Reputation: 5911

Java java.util.function.Consumer when argument needs to be transformed

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.

Upvotes: 0

Views: 126

Answers (1)

Alanpatchi
Alanpatchi

Reputation: 1199

Your operation3 is pretty straightforward.

executionMap
    .put("operation3", ((Consumer<String>)this.getEntity()::setAStringValueA)
    .andThen(this.getEntity()::setAStringValueB));

Upvotes: 1

Related Questions