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));
}
Stream.map()and go from there.Function.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 writecfg -> expression. Now, also remove all obsolete brackets and you have halved the code…