I've encountered the following problem:
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?
Here is the code example:
public class MyMapper {
MyMapper() {
Object someObject = new Person();
final var listOfObjects = List.of(someObject);
final var listOfPerson = toListOfPerson(listOfObjects);
}
List<Optional<Person>> toListOfPerson(Object object) {
return ((List) object).stream()
.map(this::toPerson)
.collect(Collectors.toList());
}
Optional<Person> toPerson(Object object) {
if (object instanceof Person) {
return Optional.of((Person) object);
}
return Optional.empty();
}
public class Person {}
}