我的返回 Optional 的方法不能以类似功能的方式使用

My method returning an Optional cannot be used in a functional-like way

我正在编写一种方法,旨在以递归方式搜索嵌套集合中的值和 return 包含该值的集合:

@SuppressWarnings("unchecked")
public static <E,
               R extends Collection<? extends E>> Optional<R> findRecursively(Collection<?> collection, E element)
                  throws ClassCastException {
   if (collection.isEmpty())
      return Optional.ofNullable(null);

   boolean nested = collection.stream()
                              .allMatch(e -> isSubclass(e.getClass(), Collection.class));
   for (Object c : collection) {
      R result;

      if (nested) {
         Optional<R> recursiveResult = findRecursively((Collection<?>) c, element);
         result = recursiveResult.orElse(null);
      } else {
         result = c.equals(element) ? (R) collection : null;
      }

      if (result != null)
         return Optional.of(result);
   }
   return Optional.ofNullable(null);
}

这工作正常,但是当我使用该方法时,如果不先将其提供给变量,我将无法直接使用 returned 可选:

Collection<String> collection = null;
Set<String> set = Util.findRecursively(collection, "")
                      .orElseThrow(RuntimeException::new);

在那种情况下,编译器无法知道方法的 return 类型。 我不知道有什么好的可能性让它发挥作用。

我想出了另外两种方法,也不是很好:

  1. 我添加了一个类型为 return 的参数,应该 return 像这样编辑:

    public static <E,
                   R extends Collection<E>> Optional<R> findRecursively(Collection<?> collection,
                                                                        E element,
                                                                        Class<R> returnType) {...
    

    但我不喜欢这样,因为附加参数(实际上)是不必要的,并且使该方法不太容易理解。

  2. 我 return 只是集合对象,而不是可选的。但是在那种情况下,我不能直接通过调用它来创建一个可选的:

    Collection<String> collection = null;
    Set<String> set = Optional.ofNullable(Util.findRecursively(collection, ""))
                              .orElseThrow(RuntimeException::new);
    

    因为编译器再次不知道 return 类型,无法推断 of() 方法的类型参数。

有人知道这个问题的好的解决方案吗?或者建议去这里走哪条路?

您可以在同一行中声明具体类型而无需声明 var:

Util.<Collection, String, Set<String>>findRecursively(collection, "")...