Before moving on to the solution, first, we will understand the question with the help of an example:
Suppose the given list is of size 11
// Given List List<Integer> list = new ArrayList(Arrays.asList(1,2,3,4,5,6,7,8,9,10,11)); // Print the above list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Read Also: How to iterate list of lists in Java
Output:
We have to split the above list into the size of 3:
// Partition into Size of 3 [1,2,3] [4,5,6] [7,8,9] [10,11]
Split list into size of 4:
// Partition into Size of 4 [1,2,3,4] [5,6,7,8] [9,10,11]
Solution:
1. Using Java82. Using Guava library
3. Using Apache Commons Library
1. Using Java8
Using Java8 we can easily break a list into batches.import java.util.*; import java.util.stream.Collectors; import java.util.concurrent.atomic.AtomicInteger; public class SplitArrayList { public static void main(String args[]) { List<Integer> list = new ArrayList(Arrays.asList(1,2,3,4,5,6,7,8,9,10,11)); /* Change the value of chunkSize to get desired number of elements in the subLists */ int chunkSize = 5; AtomicInteger counter = new AtomicInteger(); final Collection<List<Integer>> partitionedList = list.stream().collect(Collectors.groupingBy(i -> counter.getAndIncrement() / chunkSize)) .values(); for(List<Integer> subList : partitionedList) { System.out.println(subList); } } }
Output:
[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
[11]
2. Using Guava Library
You can achieve the same result by adding the Guava library to your project and using the Lists.partition method as shown below:List<Integer> inputList = new ArrayList(Arrays.asList(1,2,3,4,5,6,7,8,9,10,11)); int chunkSize = 5; List<List<Integer>> partitionedList = Lists.partition(inputList, chunkSize);
3. Using Apache Commons Library
Just like the Guava library, Apache Commons Collections4 also has the partition method in ListUtils class. You have to import the ListUtils class which is present in the following package:import org.apache.commons.collections4.ListUtils;
List<Integer> inputList = new ArrayList(Arrays.asList(100, 101, 102, 103, 104, 105)); /* Change the value of chunkSize to get desired number of elements in each of the partitionedList */ int chunkSize = 5; List<List<Integer>> partitionedList = ListUtils.partition(inputList, chunkSize);
That's all for today, please mention in the comments in case you have any questions related to the split an ArrayList in multiple small ArrayLists in Java.