1

In one of the method we used lambda expression (below) nesting streams.

return req.gUs().stream()
.map((**cfg) -> {
.filter(Optional::isPresent)
.map(Optional::get);

I want to move part of the code using some helper methods and method reference (below).

(cfg) -> {
return rsp.getUs().stream()
.filter(result.getId())    
.map((result) -> gEvent(index, Builder, cfg));

Any suggestions are greatly appreciated.

4
  • Look at the signature of Stream.map() and go from there. Commented Mar 8, 2017 at 7:04
  • Besides the nested lambdas (your cfg -> {} method should really be moved to its own method), the method looks fine to me. Commented Mar 8, 2017 at 7:04
  • What you need is Function Commented Mar 8, 2017 at 7:05
  • There is no sense in using .map(function_returning_stream).flatMap(stream -> stream); you can just use .flatMap(function_returning_stream) in the first place. Further, there is no need to write (cfg) -> { return expression; }, you can just write cfg -> expression. Now, also remove all obsolete brackets and you have halved the code… Commented Mar 8, 2017 at 17:50

1 Answer 1

1

You can make a method, that returns a Function:

return req.getUs().stream()
.map(myFunction(rsp, index, headerBuilder))
.flatMap(stream -> stream)
.filter(Optional::isPresent)
.map(Optional::get);

private Function<CFGType, GenerateReturnType> myFunction(RspType rsp, IndexType index, HeaderType header){
  return (cfg) -> {
    return rsp.getPerUs().stream()
    .filter((result) -> cfg.getId() == result.getId())
    .filter((result) -> result.getCode() == ResultCode.SUCCESS)
    .map((result) -> generateEvent(index, headerBuilder, cfg));
  }
}

Or you could use a method reference if the rsp, index and header are fields:

return req.getUs().stream()
.map(this::myFunction)
.flatMap(stream -> stream)
.filter(Optional::isPresent)
.map(Optional::get);

private GenerateType myFunction(CFGType cfg) {
  return rsp.getUs().stream()
  .filter((result) -> cfg.getUsChId() == result.getChId())
  .filter((result) -> result.getResultCode() == ResultCode.SUCCESS)
  .map((result) -> generateEvent(index, headerBuilder, cfg));
}
Sign up to request clarification or add additional context in comments.

3 Comments

Ok, I made a typo in the myFunction signature. Should be myFunction(CFGType cfg).
And I assumed, that rsp is a field in the class.
The CFGType, RspType and GenerateRemoveEventReturnType just the placeholders for the types which are written somewhere in the rest of your class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.