I have a stream of data recordStream
that I am collecting into a Map
. Using a chain like this.
recordStream
.filter(Objects::nonNull)
.map(RoomSchedule::new)
.map(roomSchedule -> roomSchedule.flipIfNeeded(processingDate))
.filter(roomSchedule -> roomSchedule.shouldBeConsidered(processingDate))
.flatMap(r -> r.getSlotAllocations(processingDate).parallelStream())
.collect(toMap(
r -> r,
r -> 1,
Integer::sum
));
However, I found that I was copying that code over and over again when I wanted to run tests with different streams. I was wondering if there's a good way of refactoring the stream such that I do.
recordStream.makeMap()
so I can reuse it.
As I typed the question, the idea that popped in my head was...
public class MyRecordStream extends Stream<MyStuff> {
// (Now wondering if there's a Lomboky way of doing this wrapper)
MyRecordStream(Stream<MyStuff> s) {
this.s = s;
}
private final Stream<MyStuff> s;
// (wrap all the other methods in stream... ugh)
public Map makeMap() {
return s
.filter(Objects::nonNull)
.map(RoomSchedule::new)
.map(roomSchedule -> roomSchedule.flipIfNeeded(processingDate))
.filter(roomSchedule -> roomSchedule.shouldBeConsidered(processingDate))
.flatMap(r -> r.getSlotAllocations(processingDate).parallelStream())
.collect(toMap(
r -> r,
r -> 1,
Integer::sum
));
}
One possibility I saw was the answer https://stackoverflow.com/a/45971597/242042 but I can't seem to get it working in a type safe manner. The solution wraps the original stream and gives it additional operations. But yet allows you to get back the original stream.