Search code examples
javajava-8guava

Java 8 way to loop using com.google.common.collect.Iterables.partition?


Seems like this should be simple using Stream.of in some fashion, and yet.... :)

Here is the code I would like improve (myEntryIds is list of Long several thousand items in length):

List<MyEntityType> results = new ArrayList<>();

// batch up into groups of 1000 
for (final List<Long> partitionedEntryIds : 
       com.google.common.collect.Iterables.partition(myEntryIds, 1000)) {
        results.addAll(BeanConverter.convertList(
             myJpaRepository.findAll(partitionedEntryIds)));
}

return results;

Solution

  • There's no Iterables#partition equivalent in JDK streams, but you could use Streams#stream helper and toImmutableList() collector from Guava (plus some method references which I personally like) to achieve your other goals:

    final List<MyEntityType> myEntityTypes = Streams.stream(
        Iterables.partition(myEntryIds, 1000))
        .map(myJpaRepository::findAll)
        .map(BeanConverter::convertList)
        .flatMap(List::stream)
        .collect(toImmutableList());