I have a java stream of undefined length. Now I need to load some meta data from the database and assign it to the streamed data.
I cannot:
- load all data from the stream to my RAM at once, populate the metadata and then start a new stream as this might use to much RAM.
- load the metadata for each element individually as this would flood my database with too many requests.
Thus I thought I could load the metadata in partitions from the database.
I need a method like this:
<T> Stream<List<T>> partition(Stream<T> stream, int partitionSize)
so I can use it like this
partition(dataSource.stream(), 1000)
.map(metadataSource::populate)
.flatMap(List::stream)
.forEach(this::doSomething);
I already found Guava's Iteralbes#partition but that would force me to convert the stream to an iterable, partition it and convert it to a stream again. Is there something inbuilt for the stream partitioning or is there an easy way to implement it myself?