How to Cast Objects in a Stream in Java
How can we cast all objects in a Stream to another class in Java?
Suppose we’re working with a
Stream of type
Object, and we want to cast each
Stream<Object> stream = Stream.of(objects);
1. Using manual casting
We can manually cast each object in the stream.
stream.map(obj -> (Person) obj);
We can also filter out objects that aren’t of that type.
stream.filter(obj -> obj instanceof Person) .map(obj -> (Person) obj);
Let’s try using the
cast() method available on every instance of
Filtering objects that aren’t of that type will look like this:
Instead of filtering and applying the map to cast each element, we can perform all of this using a
stream.flatMap( obj -> (obj instanceof Person) ? Stream.of((Person) obj) : Stream.empty() );
If the object is of the correct type, we’ll return a stream with the casted object, otherwise, we’ll return an empty stream.
This logic is very similar to