When using Java MongoDB Driver 4.0.4, OpenJDK 11 and following the example on MongoDB docs, seeing a compile error when using findIterable.forEach(printBlock);
Also looks like com.mongodb.Block
http://mongodb.github.io/mongo-java-driver/4.0/driver/tutorials/aggregation/ is not deprecated.
public String testLocal() {
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("cord");
MongoCollection<Document> collection1 = database.getCollection("papers");
FindIterable<Document> findIterable = collection1.find(new Document());
findIterable.forEach(printBlock);
}
public Block<Document> printBlock = new Block<Document>() {
@Override
public void apply(final Document document) {
System.out.println(document.toJson());
}
};
Error:
[ERROR] /Projects/cord/src/main/java/com/engg/java/cord/services/PrimaryService_Local.java:
[24,30] incompatible types: com.mongodb.Block<org.bson.Document> cannot be converted
to java.util.function.Consumer<? super org.bson.Document>
The documentation obviously is outdated. If you look at the javadocs for FindIterable
(http://mongodb.github.io/mongo-java-driver/4.0/apidocs/mongodb-driver-sync/com/mongodb/client/FindIterable.html) you'll see that forEach
is inherited from java.lang.Iterable
which takes a Consumer
as a parameter, not a Block
.
Thus, replace your printBlock declaration with:
public Consumer<Document> printBlock = document -> System.out.println(document.toJson());
... and all shall be fine.