-->

Java 8 stream support in MongoTemplate

2020-07-06 08:47发布

问题:

Why don't we have java 8 stream support in MongoTemplate in spring-data-mongodb-1.8.2.RELEASE.jar ?

I see that stream support have bean added in MongoRepository interface but I use pure MongoTemplate.

回答1:

In short

There is stream support but without exposing Stream on MongoOperations.

Explanation

Spring Data Mongo has stream support by exposing CloseableIterator<T> stream(final Query query, final Class<T> entityType). It does not use the Stream type on MongoOperations because Spring Data Mongo supports Java back to 1.6. You can obtain the Stream object by using StreamUtils.createStreamFromIterator(Iterator<T>). StreamUtils takes care of closing the stream and releasing resources.

HTH, Mark



回答2:

Mark's answer is correct (and should stay the accepted answer). Maybe a few more details on why you don't find a Stream on the MongoTemplate:

The core reason that there's no Stream on the MongoTemplate level is that Spring Data MongoDB is still compatible with Java 6. So we can't use Java 8 types in method signatures of classes we provide. With repositories, it's a different story as that's user code we inspect at runtime and — if Java 8 is present — dynamically adapt to, e.g. by converting the CloseableIterator<T> into a Stream.