Process Java Collection in batches
The following snippets shows how to process a given Java Collection (List / Set) in batches and process each batch in sequence or parallel. Split a given collection into batches int batchSize = 2 ; List < String > input = List .of( "apple" , "banana" , "orange" , "mango" , "peach" ); List < List < String >> batches = IntStream .range( 0 , input . size ()) . boxed () . collect ( Collectors .groupingBy( index -> index / batchSize )) . values () . stream () . map ( indices -> indices . stream (). map ( input :: get ). toList ()) . toList (); batches . forEach ( values -> System . out . println ( "values = " + values )); Parallel process collection in batches using Java's ForkJoin.commonPool() int batchSize = 2 ; List < String > input = List .of( "apple" , "banana" , "orange" , "mango" , "peach" ); List < List ...