I wish instead of writing my own method or class I could just check and cast the content of an optional to another class or have an empty object.
For this sub-problem in the application I want to have the custom user object of an instance of TreeNode casted to CustomUserObject, provided that the TreeNode is an instance of DefaultMutableTreeNode.
private Optional<CustomUserObject> getCustomUserObject(TreeNode node) {
Optional<DefaultMutableTreeNode> optDefaultMutableTreeNode = OptionalUtil.cast(Optional.ofNullable(node), DefaultMutableTreeNode.class);
Optional<Object> optUserObject = optDefaultMutableTreeNode.map(DefaultMutableTreeNode::getUserObject); //
return OptionalUtil.cast(optUserObject, CustomUserObject.class);
}
/**
* Maps the given optional, if the containing element is an instance of the given class.
* Returns empty if the containing object is not an instance of the given class.
*
* @param orgOptional
* given optional
* @param clazz
* given class.
* @return the resulting {@link Optional}.
*/
public static <T, X> Optional<T> cast(Optional<X> orgOptional, Class<T> clazz) {
return orgOptional //
.filter(clazz::isInstance) // check instance
.map(clazz::cast); // cast
}
/**
* Maps the given stream, if the containing element is an instance of the given class.
* Returns empty if the containing object is not an instance of the given class.
*
* @param orgStream
* given optional
* @param clazz
* given class.
* @return the resulting {@link Optional}.
*/
public static <T, X> Stream<T> cast(Stream<X> orgStream, Class<T> clazz) {
return orgStream //
.filter(clazz::isInstance) // check instance
.map(clazz::cast); // cast
}
I remember I need to cast optionals or streams in this way quite often. It is not fluent. Actually I wish java Optional or Stream would have a cast method which does the above step. I don't want to write my own fluent CustomOptional. Did I miss anything? Is there any way to do this in a simpler way?