001package ca.uhn.fhir.util; 002 003/*- 004 * #%L 005 * HAPI FHIR - Core Library 006 * %% 007 * Copyright (C) 2014 - 2023 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 java.util.ArrayList; 024import java.util.Collection; 025import java.util.List; 026import java.util.function.Consumer; 027 028/** 029 * This utility takes an input collection, breaks it up into chunks of a 030 * given maximum chunk size, and then passes those chunks to a consumer for 031 * processing. Use this to break up large tasks into smaller tasks. 032 * 033 * @since 6.6.0 034 * @param <T> The type for the chunks 035 */ 036public class TaskChunker<T> { 037 038 public void chunk(Collection<T> theInput, int theChunkSize, Consumer<List<T>> theBatchConsumer) { 039 List<T> input; 040 if (theInput instanceof List) { 041 input = (List<T>) theInput; 042 } else { 043 input = new ArrayList<>(theInput); 044 } 045 for (int i = 0; i < input.size(); i += theChunkSize) { 046 int to = i + theChunkSize; 047 to = Math.min(to, input.size()); 048 List<T> batch = input.subList(i, to); 049 theBatchConsumer.accept(batch); 050 } 051 } 052 053}