Skip to main content
added 132 characters in body
Source Link

I asked a separate question about that construct

I asked a separate question about that construct

Source Link

Utilizing the technique in https://stackoverflow.com/questions/39980133/java-8-extending-streamt/45971597#45971597 I created the following class (I just don't like the unchecked suppression)

public interface RoomScheduleStream<T extends RoomSchedule> {

    Stream<T> stream();

    @NotNull
    static <U extends RoomSchedule> RoomScheduleStream<U> of(Stream<U> delegate) {
        return () -> delegate;
    }

    @SuppressWarnings("unchecked")
    default RoomScheduleStream<T> flipAndFiltered(final LocalDate processingDate) {
        return (RoomScheduleStream<T>) of(stream()
            .map(roomSchedule -> roomSchedule.flipIfNeeded(processingDate))
            .filter(roomSchedule -> roomSchedule.shouldBeConsidered(processingDate))
        );
    }

    default Stream<RoomSlotAllocation> allocations(final LocalDate processingDate) {
        return stream()
            .flatMap(r -> r.getSlotAllocations(processingDate).parallelStream());
    }

    default Map<RoomSlotAllocation, Integer> collect(final LocalDate processingDate) {
        return allocations(processingDate)
            .collect(roomCollector());
    }

    default Map<RoomSlotAllocation, Integer> filterAndCollect(final LocalDate processingDate) {
        return flipAndFiltered(processingDate)
            .collect(processingDate);
    }

    static Collector<RoomSlotAllocation, ?, Map<RoomSlotAllocation, Integer>> roomCollector() {
        return toMap(
            r -> r,
            r -> 1,
            Integer::sum
        );
    }

}

This allows me to refactor to

Map<RoomSlotAllocation, Integer> allocationMap =
   RoomScheduleStream
     .of(roomScheduleStream)
     .filterAndCollect(processingDate);

In addition this allows me to refactor to the following in case I want to inject a peek for specific tests where I want to validate the output (in this case I used println, but those could be asserts)

Map<RoomSlotAllocation, Integer> allocationMap =
  RoomScheduleStream
    .of(roomScheduleStream)
    .flipAndFiltered(processingDate)
    .allocations(processingDate)
    .peek(System.out::println)
    .collect(RoomScheduleStream.roomCollector());

TBH... I have no clue how this part of the code compiles, but that was derived from the original StackOverflow answer

static <U extends RoomSchedule> RoomScheduleStream<U> of(Stream<U> delegate) {
    return () -> delegate;
}