I have the following method and at here I first get name of exportProductType and then get the value of that name. If name or the valueOf(name) is null, then throw exception.
public static ProductType getExportProductType(ExportProductType exportProductType) {
return Optional.ofNullable(exportProductType)
.map(ExportProductType::name)
.map(ProductType::valueOf)
.orElseThrow(() -> new ProductTypeNotFoundException());
}
Everything is ok and works without any problem. However, when I pass exportProductType enum value that is not available in ProductType enums, I cannot catch it and it throws another exception "No enum constant...". So, I think I need to check if ProductType::valueOf is null before .map(ProductType::valueOf). How should I check it? Using a boolean or filter? Or another way that is proper for stream() in Java?
I think something like that after .map(ExportProductType::name):
.filter(result -> ProductType::valueOf(result) != null)
Update: I found a proper way as shown below:
EnumUtils.isValidEnum(ProductType.class, exportProductType.name());
I just need to use it in stream(). So, is it possible to make the same check in a stream()? Is this ok just below the .map(ExportProductType::name) line?
.filter(x -> EnumUtils.isValidEnum(ProductType.class, x))