Is it possible to cast a stream in Java 8? Say I have a list of objects, I can do something like this to filter out all the additional objects:
Stream.of(obj
This looks a little ugly. Is it possible to cast an entire stream to a different type? Like cast
Streamto aStream?
No that wouldn't be possible. This is not new in Java 8. This is specific to generics. A List is not a super type of List, so you can't just cast a List to a List.
Similar is the issue here. You can't cast Stream to Stream. Of course you can cast it indirectly like this:
Stream intStream = (Stream) (Stream>)stream;
but that is not safe, and might fail at runtime. The underlying reason for this is, generics in Java are implemented using erasure. So, there is no type information available about which type of Stream it is at runtime. Everything is just Stream.
BTW, what's wrong with your approach? Looks fine to me.