quma
quma

Reputation: 5733

Java 8 stream - cast list items to type of subclass

I have a list of ScheduleContainer objects and in the stream each element should be casted to type ScheduleIntervalContainer. Is there a way of doing this?

final List<ScheduleContainer> scheduleIntervalContainersReducedOfSameTimes

final List<List<ScheduleContainer>> scheduleIntervalContainerOfCurrentDay = new ArrayList<>(
        scheduleIntervalContainersReducedOfSameTimes.stream()
            .sorted(Comparator.comparing(ScheduleIntervalContainer::getStartDate).reversed())
            .filter(s -> s.getStartDate().withTimeAtStartOfDay().isEqual(today.withTimeAtStartOfDay())).collect(Collectors
                .groupingBy(ScheduleIntervalContainer::getStartDate, LinkedHashMap::new, Collectors.<ScheduleContainer> toList()))
            .values());

Upvotes: 29

Views: 83661

Answers (2)

Maciej Dobrowolski
Maciej Dobrowolski

Reputation: 12122

It's possible, but you should first consider if you need casting at all or just the function should operate on subclass type from the very beginning.

Downcasting requires special care and you should first check if given object can be cast down by:

object instanceof ScheduleIntervalContainer

Then you can cast it nicely by:

Use functional method to cast like ScheduleIntervalContainer.class::cast

So, the whole flow should look like:

collection.stream()
    .filter(ScheduleIntervalContainer.class::isInstance)
    .map(ScheduleIntervalContainer.class::cast)
    // other operations

Upvotes: 80

Peter Lawrey
Peter Lawrey

Reputation: 533530

Do you mean you want to cast each element?

scheduleIntervalContainersReducedOfSameTimes.stream()
                                            .map(sic -> (ScheduleIntervalContainer) sic)
                // now I have a Stream<ScheduleIntervalContainer>

Or you could use a method reference if you feel it is clearer

                                            .map(ScheduleIntervalContainer.class::cast)

On a performance note; the first example is a non-capturing lambda so it doesn't create any garbage, but the second example is a capturing lambda so could create an object each time it is classed.

Upvotes: 39

Related Questions