1. import java.util.ArrayList;
  2. import java.util.List;
  3. public class BatchProcessor {
  4. /**
  5. * Processes a list of datasets in batches.
  6. *
  7. * @param datasets A list of datasets to process.
  8. * @param batchSize The size of each batch.
  9. * @param operation The operation to perform on each dataset.
  10. * @param flag1 An optional flag.
  11. * @param flag2 Another optional flag.
  12. */
  13. public void processBatched(List<?> datasets, int batchSize, Processor operation, Boolean flag1, Boolean flag2) {
  14. if (datasets == null || datasets.isEmpty()) {
  15. return;
  16. }
  17. int numDatasets = datasets.size();
  18. int start = 0;
  19. while (start < numDatasets) {
  20. int end = Math.min(start + batchSize, numDatasets); // Calculate end index for the current batch
  21. List<?> batch = datasets.subList(start, end); // Extract the batch
  22. processBatch(batch, operation, flag1, flag2); // Process the batch
  23. start = end; // Update the start index for the next batch
  24. }
  25. }
  26. private void processBatch(List<?> batch, Processor operation, Boolean flag1, Boolean flag2) {
  27. for (Object dataset : batch) {
  28. operation.process(dataset, flag1, flag2); // Process each dataset in the batch
  29. }
  30. }
  31. /**
  32. * Functional interface for the processing operation.
  33. */
  34. @FunctionalInterface
  35. public interface Processor {
  36. void process(Object dataset, Boolean flag1, Boolean flag2);
  37. }
  38. public static void main(String[] args) {
  39. // Example Usage
  40. List<String> data = new ArrayList<>();
  41. data.add("Data 1");
  42. data.add("Data 2");
  43. data.add("Data 3");
  44. data.add("Data 4");
  45. data.add("Data 5");
  46. data.add("Data 6");
  47. data.add("Data 7");
  48. data.add("Data 8");
  49. BatchProcessor processor = new BatchProcessor();
  50. // Example operation: Print the data with flags
  51. Processor printProcessor = (dataset, flag1, flag2) -> {
  52. System.out.println("Processing: " + dataset + ", Flag1: " + flag1 + ", Flag2: " + flag2);
  53. };
  54. // Process in batches of size 3, with flag1 set to true
  55. processor.processBatched(data, 3, printProcessor, true, false);
  56. }
  57. }

Add your comment