title: How to map an instance of type Object to specific Class in Java using Stream API
body: <p>I've encountered the following problem:</p>
  <p>If I map an object in a stream to a specific class in Java, the java stream API does not recognize a specific object after the mapping and still assumes it is an object. What am I doing wrong, and is there a way to solve this without potential class cast exceptions?</p>
  <p>Here is the code example:</p>
  <pre><code>public class MyMapper {
  
          MyMapper() {
              Object someObject = new Person();
              final var listOfObjects = List.of(someObject);
              final var listOfPerson = toListOfPerson(listOfObjects);
          }
  
          List&lt;Optional&lt;Person&gt;&gt; toListOfPerson(Object object) {
              return ((List) object).stream()
                             .map(this::toPerson)
                             .collect(Collectors.toList());
          }
  
          Optional&lt;Person&gt; toPerson(Object object) {
  
              if (object instanceof Person) {
                  return Optional.of((Person) object);
              }
              return Optional.empty();
          }
  
          public class Person {}
  }
  </code></pre>