在MongoDB中的文档上使用forEach [英] Using forEach on Documents in MongoDB
问题描述
我正在此一个>.
我不明白为什么以下含义意味着以JSON格式打印每个文档.这就是forEach
的工作方式,以及为什么为每个Document
I am following this.
I am unable to understand why the following would mean print each Document in JSON format. That is how forEach
works and why the method name apply
is run for each Document
Block<Document> printBlock = new Block<Document>() {
@Override
public void apply(final Document document) {
System.out.println(document.toJson());
}
};
collection.find(new Document()).forEach(printBlock);
推荐答案
这是因为 MongoIterable 已声明 forEach 方法://docs.oracle.com/javase/7/docs/api/java/lang/Iterable.html?is-external = true"rel =" nofollow noreferrer>可迭代,其中没有forEach
方法完全没有.
This is because the find operation return a MongoIterable which has declared a forEach method for java-7 Iterable which has no forEach
method at all.
因此您可以调用 MongoIterable .在java8中, Iterable 包括
So you can call the forEach method on a MongoIterable as in your question. In java8, the Iterable includes the forEach(Consumer) operation. if you use forEach
with inlined Lambda Expression or Method Reference Exception in java8, you must to cast the lambda to the explicit target type, for example:
collection.find(new Document())
.forEach( it-> System.out.println(it.toJson())); // compile-error
// worked with inlined lambda expression
collection.find(new Document())
.forEach((Consumer<Document>) it -> System.out.println(it.toJson()));
collection.find(new Document())
.forEach((Block<Document>) it -> System.out.println(it.toJson()));
// worked with method reference expression
collection.find(new Document())
.forEach((Consumer<Document>) printBlock::apply);
collection.find(new Document())
.forEach((Block<Document>) printBlock::apply);
有关lambda表达式的更多详细信息,请参见此处.
For more details about lambda expression you can see here.
这篇关于在MongoDB中的文档上使用forEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!