Apache Common Collections framework provide a facility to divide a given into multiple sub list based on a given size. The final list may be smaller than the give size.
The below code will show how to do it.
1 import java.util.ArrayList;
2 import java.util.List;
3
4 import org.apache.commons.collections4.ListUtils;
5
6 public class Example5 {
7 public static void main(String[] args) {
8 List list1 = new ArrayList();
9
10 list1.add(1);
11 list1.add(2);
12 list1.add(3);
13 list1.add(4);
14 list1.add(5);
15 list1.add(10);
16 list1.add(9);
17 list1.add(8);
18 list1.add(7);
19 list1.add(6);
20
21 List<List> list = ListUtils.partition(list1, 2);
22
23 for(List innerList : list) {
24 System.out.println("New List");
25 for(Integer data : innerList) {
26 System.out.println(data);
27 }
28 }
29 }
30 }
Explanation
In the above code, I have created a unsorted list named list1.
Then at line 21, I call partition method of ListUtils utility class. The methods take two arguments.
1) The list which has to be partitioned
2) The size of each sub list after partition.
Output
New List
1
2
New List
3
4
New List
5
10
New List
9
8
New List
7
6