nagylzs
nagylzs

Reputation: 4180

Stream collect from MongoIterable in Java

Is it possible to convert a MongoDb query result into a stream and collect it?

For example, to get a list of _id values, something like this:

getMongoDatabaseInstance()
                .getCollection("some_collection_name")
                .find()
                .projection(new Document("_id", 1 ))
                .map(d -> d.getString("_id") )
                .collect(Collectors.toList());

This results in a compilation error:

The method collect(Collectors.toList()) is undefined for the type MongoIterable<String>

because a MongoIterable is not a stream and cannot be collected.

Of course, I could declare a cursor and iterate over the result set, but that requires adding declarations and loops etc. I need to collect small number of documents at many places in my program, and it would be much more clean and easy to convert them to a stream and collect.

Is that possible?

Upvotes: 0

Views: 2417

Answers (1)

Hadi
Hadi

Reputation: 17299

Try use StreamSupport#stream By using this utility you can convert iterable interface to stream or parallel stream.

StreamSupport.stream(getMongoDatabaseInstance()
             .getCollection("some_collection_name")
             .find()
             .projection(new Document("_id", 1 )).spliterator(),false)
             .map(d->d.getString("_id"))
             .collect(Collectors.toList());

Upvotes: 3

Related Questions