Open In App

How to Split an ArrayList in Multiple Small ArrayLists?

In Java, ArrayList is a pre-defined class of the Java collection framework, and it can be used to add the elements dynamically. One more special feature is that it can shrink the size dynamically to add or remove the elements from the ArrayList.

In this article, we will discuss how to split an ArrayList into multiple small ArrayLists.

Step-by-Step Implementation

Program to split an ArrayList in multiple small ArrayLists in Java




// Java Program to split an ArrayList in multiple small ArrayLists
import java.util.ArrayList;
import java.util.List;
  
public class GFGSplitArrayList {
  //main method
    public static void main(String[] args) {
          
      //create the mainList ArrayList
        ArrayList<String> mainList = new ArrayList<>();
      // Adding values into ArrayList of Strings
        mainList.add("C");
        mainList.add("Java");
        mainList.add("Python");
        mainList.add("HTML");
        mainList.add("CSS");
        mainList.add("Six");
        mainList.add("Spring");
        mainList.add("Hibernate");
        mainList.add("NodeJs");
  
        // Split the ArrayList into smaller ArrayLists with size 3
        int subListSize = 3;
        List<ArrayList<String>> subLists = splitArrayList(mainList, subListSize);
  
        // print the result
        for (int i = 0; i < subLists.size(); i++) {
            System.out.println("Sublist " + (i + 1) + ": " + subLists.get(i));
        }
    }
  
    // Method to split an ArrayList into smaller ArrayLists
    private static <T> List<ArrayList<T>> splitArrayList(ArrayList<T> original, int size) {
        List<ArrayList<T>> subLists = new ArrayList<>();
  
        for (int i = 0; i < original.size(); i += size) {
            int end = Math.min(i + size, original.size());
            subLists.add(new ArrayList<>(original.subList(i, end)));
        }
  
        return subLists;
    }
}

Output
Sublist 1: [C, Java, Python]
Sublist 2: [HTML, CSS, Six]
Sublist 3: [Spring, Hibernate, NodeJs]



Explanation of the above Program:


Article Tags :