0

I have list of number which I want to process in batches.

example 1:

input1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] //(List of number)
input2 = 5 //(Batch size)
output = [[1, 2, 3, 4, 5], [6, 7, 8, 9]]

example 2:

input1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]//(List of number) 
input2 = 5//(Batch size)
output = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]

2 Answers2

1

Here is an example using a java stream ,

 public static void main(String[] args) throws Exception {

        List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11));
        int batchSize = 5;
        AtomicInteger ai = new AtomicInteger();

        Collection<List<Integer>> chunkedOrders = list.stream()
                .collect(Collectors.groupingBy(item -> ai.getAndIncrement() / batchSize)).values();

        System.out.println("Your innerlist = " + chunkedOrders);

        chunkedOrders.forEach(chunk -> {
            System.out.println("Processing" + " " + chunk.size() + " " + " data, sublist = " + chunk);

        });

    }

Output:

Your innerlist = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11]]
Processing 5  data, sublist = [1, 2, 3, 4, 5]
Processing 5  data, sublist = [6, 7, 8, 9, 10]
Processing 1  data, sublist = [11]
Sibin Rasiya
  • 1,132
  • 1
  • 11
  • 15
0
public class Solution {

    public static <T> List<List<T>> breaks(List<T> tList, int length) {
        if (length <= 0)
            throw new IllegalArgumentException(
                    "The chosen length is less than or equal to zero: " + length
            );
        int size = tList.size();
        if (size <= 0)
            return new ArrayList<>();
        int fullChunks = (size - 1) / length;
        return IntStream.range(0, fullChunks + 1).mapToObj(
                n -> tList.subList(n * length, n == fullChunks ? size : (n + 1) * length)
        ).collect(Collectors.toList());
    }

    public static void main(String args[]) {

        // Original list
        List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14);
        // Printing of the original list
        System.out.println(list1);
        // Broken list
        List<List<Integer>> list2 = breaks(list1,5);
        // Print of the broken list
        System.out.println(list2);

    }

}
Federico Galimberti
  • 185
  • 1
  • 3
  • 11