我有一个ScheduleContainer
对象列表,在流中,每个元素都应该被输入到类型中ScheduleIntervalContainer
.有办法做到这一点吗?
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());
Run Code Online (Sandbox Code Playgroud)
Mac*_*ski 28
这是可能的,但是您应该首先考虑是否需要进行转换,或者只是函数应该从一开始就对子类类型进行操作.
向下转换需要特别小心,您应首先检查给定的对象是否可以通过以下方式进行转换:
object instanceof ScheduleIntervalContainer
Run Code Online (Sandbox Code Playgroud)
然后你可以通过以下方式很好地施展它:
(ScheduleIntervalContainer) object
Run Code Online (Sandbox Code Playgroud)
所以,整个流程应如下所示:
collection.stream()
.filter(obj -> obj instanceof ScheduleIntervalContainer)
.map(obj -> (ScheduleIntervalContainer) obj)
// other operations
Run Code Online (Sandbox Code Playgroud)
Pet*_*rey 22
你的意思是你想要投射每个元素吗?
scheduleIntervalContainersReducedOfSameTimes.stream()
.map(sic -> (ScheduleIntervalContainer) sic)
// now I have a Stream<ScheduleIntervalContainer>
Run Code Online (Sandbox Code Playgroud)
或者,如果您觉得它更清晰,您可以使用方法参考
.map(ScheduleIntervalContainer.class::cast)
Run Code Online (Sandbox Code Playgroud)
在表演笔记上; 第一个例子是非捕获lambda,因此它不会产生任何垃圾,但第二个例子是捕获lambda,因此每次分类时都可以创建一个对象.
归档时间: |
|
查看次数: |
33016 次 |
最近记录: |