How to Split an ArrayList in Multiple Small ArrayLists?
Last Updated :
01 Feb, 2024
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
- Create a String ArrayList named as mainList.
- Add the values into the mainList ArrayList.
- Define the subList size and write another method named splitArrayList with two parameters ArrayList, and SubList size.
- The splitArrayList method accepts two parameters ArrayList and subList size and it can convert the ArrayList into subList based on the size of the subList size.
- Print the sub ArrayList.
Program to split an ArrayList in multiple small ArrayLists in Java
Java
import java.util.ArrayList;
import java.util.List;
public class GFGSplitArrayList {
public static void main(String[] args) {
ArrayList<String> mainList = new ArrayList<>();
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" );
int subListSize = 3 ;
List<ArrayList<String>> subLists = splitArrayList(mainList, subListSize);
for ( int i = 0 ; i < subLists.size(); i++) {
System.out.println( "Sublist " + (i + 1 ) + ": " + subLists.get(i));
}
}
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:
- In above example, we convert the ArrayList split into the 3 sub ArrayList with the size of 3 in sub ArrayList.
- First define the main ArrayList names as mainList and added the values into the mainList.
- After that define the size of sub ArrayList then iterate the main ArrayList adding the values into the subList of the program.
Share your thoughts in the comments
Please Login to comment...