Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 stream - cast list items to type of subclass

Tags:

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());
like image 690
quma Avatar asked Mar 02 '16 09:03

quma


People also ask

How do you cast a List in Java?

Try the following: List<TestA> result = new List<TestA>(); List<TestB> data = new List<TestB>(); result. addAll(data);

Can we convert Stream to List in Java?

Stream class has toArray() method to convert Stream to Array, but there is no similar method to convert Stream to List or Set. Java has a design philosophy of providing conversion methods between new and old API classes e.g. when they introduced Path class in JDK 7, which is similar to java.

How can we get a Stream from a List in Java?

Using List. stream() method: Java List interface provides stream() method which returns a sequential Stream with this collection as its source.


1 Answers

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 casted 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(obj -> obj instanceof ScheduleIntervalContainer)
    .map(ScheduleIntervalContainer.class::cast)
    // other operations
like image 64
Maciej Dobrowolski Avatar answered Sep 17 '22 14:09

Maciej Dobrowolski