001package ca.uhn.fhir.util; 002 003/*- 004 * #%L 005 * HAPI FHIR - Core Library 006 * %% 007 * Copyright (C) 2014 - 2024 Smile CDR, Inc. 008 * %% 009 * Licensed under the Apache License, Version 2.0 (the "License"); 010 * you may not use this file except in compliance with the License. 011 * You may obtain a copy of the License at 012 * 013 * http://www.apache.org/licenses/LICENSE-2.0 014 * 015 * Unless required by applicable law or agreed to in writing, software 016 * distributed under the License is distributed on an "AS IS" BASIS, 017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 018 * See the License for the specific language governing permissions and 019 * limitations under the License. 020 * #L% 021 */ 022 023import jakarta.annotation.Nonnull; 024 025import java.util.ArrayList; 026import java.util.Collection; 027import java.util.List; 028import java.util.function.Consumer; 029import java.util.stream.Stream; 030 031/** 032 * This utility takes an input collection, breaks it up into chunks of a 033 * given maximum chunk size, and then passes those chunks to a consumer for 034 * processing. Use this to break up large tasks into smaller tasks. 035 * 036 * @since 6.6.0 037 * @param <T> The type for the chunks 038 */ 039public class TaskChunker<T> { 040 041 public void chunk(Collection<T> theInput, int theChunkSize, Consumer<List<T>> theBatchConsumer) { 042 List<T> input; 043 if (theInput instanceof List) { 044 input = (List<T>) theInput; 045 } else { 046 input = new ArrayList<>(theInput); 047 } 048 for (int i = 0; i < input.size(); i += theChunkSize) { 049 int to = i + theChunkSize; 050 to = Math.min(to, input.size()); 051 List<T> batch = input.subList(i, to); 052 theBatchConsumer.accept(batch); 053 } 054 } 055 056 @Nonnull 057 public <T> Stream<List<T>> chunk(Stream<T> theStream, int theChunkSize) { 058 return StreamUtil.partition(theStream, theChunkSize); 059 } 060}