Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 550
Carrein Avatar asked Dec 26 '17 14:12

Carrein


2 Answers

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

mongoClient.listDatabaseNames()
           .forEach((Consumer<String>) System.out::println);
like image 154
Ousmane D. Avatar answered Oct 03 '22 18:10

Ousmane D.


listDatabaseNames() exposes to different forEach methods. One can receive as argument Block<? super String> block and the second one receive Consumer<? super String> consumer. In order to avoid this ambiguity you will need to cast it to your needs.

  mongoClient1.listDatabaseNames()
              .forEach((Block<String>) System.out::println);

There is also an open issue about this here

like image 22
Andrei Sfat Avatar answered Oct 03 '22 17:10

Andrei Sfat