If the field is not present you end up assigning Optional.empty() to the fieldValue variable.
Object fieldValue = objectMap.entrySet().stream()
.filter(fieldDescriptorObjectEntry -> {
Descriptors.FieldDescriptor descriptor = fieldDescriptorObjectEntry.getKey();
return descriptor.getName().equals(fieldName);
})
.findFirst().map(fieldDescriptorObjectEntry -> fieldDescriptorObjectEntry.getValue())
.orElse(Optional.empty()); // ISSUE HERE
You then return with return Optional.of(fieldValue). This means, when no field is found, you return an Optional<Optional<?>> so when doing the following:
long someUid = (long) getRequestByFieldName("some_uid").orElse(0);
The orElse bit is never called because the Optional is never empty. Instead, it holds an Optional which obviously can't be cast to Long. From your code, you should be able to simply return the result of map, like so:
return objectMap.entrySet().stream()
.filter(fieldDescriptorObjectEntry -> {
Descriptors.FieldDescriptor descriptor = fieldDescriptorObjectEntry.getKey();
return descriptor.getName().equals(fieldName);
})
.findFirst()
.map(fieldDescriptorObjectEntry -> fieldDescriptorObjectEntry.getValue());
Whether or not this completely solves the casting problem depends on how you determine what type of object the Optional holds.