为什么 Java 无法在此代码中正确推断类型?

Why isn't Java able to infer the type correctly in this code?

代码仅供演示。

这不编译:

public static void main(String[] args) {
   final List<Optional<Dog>> dogs = Arrays.stream(new String[]{"a", "b"})
       .map((code) -> {
         try {
           return Optional.of(new Dog());
         } catch (RuntimeException e) {
           return Optional.empty();
         }
       })
       .collect(Collectors.toList());
 }

class Dog{}

这确实编译:

public static void main(String[] args) {
   final List<Optional<Dog>> dogs = Arrays.stream(new String[]{"a", "b"})
       .map((code) -> getDog(code))
       .collect(Collectors.toList());
 }

 private static Optional<Dog> getDog(String code) {
   try {
     return Optional.of(new Dog());
   } catch (RuntimeException e) {
     return Optional.empty();
   }
 }

class Dog{}

有没有其他方法可以告诉Java第一个例子中Optional.empty()的类型是Optional<Dog>类型?

Is there any other way to tell Java that the type of Optional.empty() in the first example is of type Optional<Dog>?

Optional.<Dog>empty()

调用带有模板参数的静态方法时,使用上述语法显式指定参数。

显示在The Java™ Tutorials页面上:

public class Util {
    public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) {
        return p1.getKey().equals(p2.getKey()) &&
               p1.getValue().equals(p2.getValue());
    }
}

The complete syntax for invoking this method would be:

Pair<Integer, String> p1 = new Pair<>(1, "apple");
Pair<Integer, String> p2 = new Pair<>(2, "pear");
boolean same = Util.<Integer, String>compare(p1, p2);