Search code examples
javamongodblambda

Ambiguous reference to forEach when listing mongoDB's database in Java


I'm following this guide to try and setup a mongoDB database.

mongoClient.listDatabaseNames().forEach(System.out::println);

getDatabaseNames() is deprecated and replaced.

However this line gives the following error:

error: reference to forEach is ambiguous
    mongoClient.listDatabaseNames().forEach(System.out::println);
                                   ^
  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

The documentation states that listDatabaseNames() returns a ListDatabasesIterable, why can I not iterate through this list?


Solution

  • You can help the compiler resolve the ambiguity by casting to Consumer<String>

    mongoClient.listDatabaseNames()
               .forEach((Consumer<String>) System.out::println);