Java MongoDB - 指定使用哪个forEach

时间:2017-10-30 20:35:52

标签: java mongodb foreach

我将Java 8和MongoDriver 3.5用于Java项目

我使用方法FindIterable<Document>检索collection.find(),我想在此Iterable上使用 forEach ,但我的forEach存在问题

到目前为止,这是我的代码

MongoDatabase database = this.mongoClient.getDatabase(url);
MongoCollection<Document> collection = database.getCollection("myCollection");

FindIterable<Document> documentList = collection.find();

documentList.forEach((Document document) -> {
    System.out.println(document.toJson());
});

Spring Tools Suite没有给我一个错误,但是当我编译代码时,我收到了以下错误

error: reference to forEach is ambiguous
documentList.forEach((Document document) -> System.out.println(document.toJson()));
                    ^
both method forEach(Consumer<? super T>) in Iterable and method forEach(Block<? super TResult>) in MongoIterable match
  where T,TResult are type-variables:
    T extends Object declared in interface Iterable
    TResult extends Object declared in interface MongoIterable

所以,我想知道,有没有办法告诉Java使用原生forEach方法而不是mongo方法? 例如在php中,您可以执行类似/ @var $ foo String /来帮助编译器

PS:我知道我可以使用for(文档文档:documentList),但是我们仍然遇到错误时光标没有关闭的问题。 (如this answer所示)但如果我的问题真的无法解决,我可以使用这个后备

1 个答案:

答案 0 :(得分:1)

您可以使用强制转换为必需的方法实现(在您的情况下是来自Iterable接口的方法):

documentList.forEach((Consumer<? super Document>) (Document document) -> {
    System.out.println(document.toJson());
});

奇怪的是Spring Tools Suite没有显示错误,同时IntelliJ Idea会显示错误,它显示“模糊方法调用”:)

相关问题