SoFunction
Updated on 2025-03-03

Example of Java's method of dividing lists into multiple lists

background

In development, sometimes I need to split a list collection into multiple small list collections for processing, for example: using multiple threads to process the split small collection asynchronously to improve efficiency. The following will split the sample collection:

The first type: equal splitting

    private List<List<String>> partition(List<String> originalList, int size) {
        List<List<String>> partition = new ArrayList<>();
        int totalSize = ();
        // Calculate the size of each set and round it up        int groupSize = (totalSize / size) + 1;

        for (int i = 0; i < size; i++) {
            int start = i * groupSize;
            // Prevent array from crossing boundaries            int end = (start + groupSize, totalSize);
            (new ArrayList<>((start, end)));
        }
        return partition;
    }

The second type: specify the number to split

    ImportgoogleofguavaToolkit
    <dependency>
      <groupId></groupId>
      <artifactId>guava</artifactId>
    </dependency>

    private List<List<String>> partition(List<String> originalList) {
        // Specify the number -> Split every 1000 into a small collection        List<List<String>> partition = (originalList, 1000);
        return partition;
    }

The third type: split according to the conditions

    private List<List<Integer>> partition() {
        List<Integer> numbers = (10, 20, 30, 40, 50, 60, 70, 80, 90);
        List<List<Integer>> groups = new ArrayList<>();
        (new ArrayList<>()); // Less than or equal to 50        (new ArrayList<>()); // Greater than 50
        for (Integer number : numbers) {
            if (number <= 50) {
                (0).add(number);
            } else {
                (1).add(number);
            }
        }
        return groups;
    }

Summarize

This is the end of this article about Java dividing lists into multiple lists. For more related Java dividing lists into multiple lists, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!