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());
Try the following: List<TestA> result = new List<TestA>(); List<TestB> data = new List<TestB>(); result. addAll(data);
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.
Using List. stream() method: Java List interface provides stream() method which returns a sequential Stream with this collection as its source.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With