2

I am using Java 8 and MongoDriver 3.5 for a Java project

I retrieve a FindIterable<Document> with the method collection.find(), and I would like to use a forEach on this Iterable, but I have a problem with my forEach

Here is my code so far

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 doesn't give me an error, however when I compile my code, I got the following error

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

So, I was wondering, is there a way to tell Java to use the native forEach method instead of the mongo one ? For example in php you can do something like /@var $foo String/ to help compiler

PS : I know I could use a for(Document document : documentList) but we still have a problem with the cursor not being closed on error. (as seen on this answer ) but if my question is really unsolvable, I can use this fallback

Alexi Coard
  • 7,106
  • 12
  • 38
  • 58

1 Answers1

4

you can use casting to required method implementation (in your case the one from Iterable interface):

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

it's strange that Spring Tools Suite doesn't display you an error, meanwhile IntelliJ Idea does, it displays "Ambiguous method call" :)

Vasyl Sarzhynskyi
  • 3,689
  • 2
  • 22
  • 55