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 Object to Person.

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);

2. Using cast()

Let’s try using the cast() method available on every instance of Class.

stream.map(Person.class::cast);

Filtering objects that aren’t of that type will look like this:

stream.filter(Person.class::isInstance)
      .map(Person.class::cast);

3. Using flatMap()

Instead of filtering and applying the map to cast each element, we can perform all of this using a flatMap().

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 flatMap(Optional::stream).