Reputation: 217
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.
Upvotes: 1
Views: 121
Reputation: 682
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));
}
Upvotes: 1