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(objects).filter(c -> c instanceof Client)
After this though, if I want to do something with the clients I would need to cast each of them:
Stream.of(objects).filter(c -> c instanceof Client)
.map(c -> ((Client) c).getID()).forEach(System.out::println);
This looks a little ugly. Is it possible to cast an entire stream to a different type? Like cast Stream<Object>
to a Stream<Client>
?
Please ignore the fact that doing things like this would probably mean bad design. We do stuff like this in my computer science class, so I was looking into the new features of java 8 and was curious if this was possible.
I don't think there is a way to do that out-of-the-box. A possibly cleaner solution would be:
Stream.of(objects)
.filter(c -> c instanceof Client)
.map(c -> (Client) c)
.map(Client::getID)
.forEach(System.out::println);
or, as suggested in the comments, you could use the cast
method - the former may be easier to read though:
Stream.of(objects)
.filter(Client.class::isInstance)
.map(Client.class::cast)
.map(Client::getID)
.forEach(System.out::println);