Java8 - 显式类型如何匹配一种变体 - 而不是其他类型?

2024-03-12

我有一个简单的片段如下。我提到this https://jira.mongodb.org/browse/JAVA-2010

List<Document> list = new LinkedList<Document>();
FindIterable<Document> itr = collection.find(findQuery)
                       .forEach((Document doc) -> list.add(doc));
return list;

它编译没有任何问题。

  1. 我想我们是在告诉编译器doc属于类型Document. 为什么需要它?

但如果我执行以下操作,它会引发不明确的错误。我提到this https://stackoverflow.com/questions/28466925/java-type-inference-reference-is-ambiguous-in-java-8-but-not-java-7但无法准确联系和理解。

collection.find(findQuery).forEach(list::add);
  1. 谁能解释一下为什么第二个声明不起作用?

  2. 有没有更好的方法来编写第一个[工作中]?

Java版本:1.8.0_231

进口声明:

import java.util.List;
import java.util.Optional;
import com.mongodb.client.FindIterable;
import org.bson.Document;

问题是forEach只是一个Consumer,它有一个方法void accept(T element),并且您正在尝试返回一个值。

第一个版本中的“不明确”错误是受其他帖子的约束 https://stackoverflow.com/questions/21873829/how-to-fix-ambiguous-type-on-method-reference-tostring-of-an-integer.

你可以这样做(我认为这更惯用)

return StreamSupport.stream(collection.find(findQuery).spliterator(), false)
                    .collect(Collectors.toList());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java8 - 显式类型如何匹配一种变体 - 而不是其他类型? 的相关文章

随机推荐