Java 8 stream - cast list items to type of subclass

后端 未结 2 1641
名媛妹妹
名媛妹妹 2021-02-07 08:47

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 t

相关标签:
2条回答
  • 2021-02-07 08:51

    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.

    0 讨论(0)
  • 2021-02-07 08:54

    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:

    (ScheduleIntervalContainer) object
    

    So, the whole flow should look like:

    collection.stream()
        .filter(obj -> obj instanceof ScheduleIntervalContainer)
        .map(obj -> (ScheduleIntervalContainer) obj)
        // other operations
    
    0 讨论(0)
提交回复
热议问题