Abh*_*ngh 4 java functional-programming java-8
我下面这个。我不明白为什么以下含义意味着以JSON格式打印每个文档。那是如何forEach
工作的,为什么每个方法名apply
都要运行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);
Run Code Online (Sandbox Code Playgroud)
这是因为find操作返回一个MongoIterable,它已为java-7 Iterable声明了一个forEach方法,而该方法根本没有任何方法。forEach
因此,您可以像在问题中一样在MongoIterable上调用forEach方法。在java8中,Iterable包含forEach(Consumer)操作。如果在java8中与内联Lambda表达式或方法引用异常一起使用,则必须将lambda强制转换为显式目标类型,例如:forEach
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);
Run Code Online (Sandbox Code Playgroud)
有关lambda表达式的更多详细信息,请参见此处。
如果你查看forEach
方法的 javadoc,它会作为Consumer
参数。Consumer
只是一个只有一个方法的函数式接口。forEach方法内部调用单个方法
在您的情况下Block
,是一个函数式接口,它只有一个方法apply
,该方法消耗一个参数并且不返回任何内容,即Consumer
您可以使用 lambda 表达式实现相同的功能,而无需实现Block
collection.find(new Document()).forEach(doc-> System.out.println(doc.toJson()));
Run Code Online (Sandbox Code Playgroud)