it is possible, with Java 8 stream API, to create Stream that is not evaluated until is necessary?
I mean.
I have a stream that processes a list of elements, in one of the middle operations (map) I have to read go through another stream and I want to have that Stream in another variable to be used through all other first stream objects, but if there Are no objects to process I would like to avoid process second stream.
I think it's easier to check with code:
Message[] process(@Nullable Message[] messages) {
Stream<Function> transformationsToApply =
transformations
.stream()
.filter(transformation -> transformationIsEnabled(transformation.getLeft()))
.map(Pair::getRight);
return Arrays.stream(messages != null ? messages : new Message[0])
.filter(Objects::nonNull)
.map(agentMessage -> {
transformationsToApply.forEach(transformation -> processMessage(transformation, agentMessage));
return agentMessage;
})
.toArray(Message[]::new);
}
My doubt is about first one stream generation, I would like to return stream based on the list that I processed, but I only to want to do if it is gonna be used (And use same for all message elemets).
Any idea..?