Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List into List of Lists that contain 10 items

Tags:

java

I have a List of pojos. To convert this List of pojos into a List of List where each sublist is of the size 10 or less. So for example a List of size 13 is converted to a two element List. The first element is a List of 10 items, the second element is a List 3 items.

So the data structure is List<List<pojo>>

To create this List of lists :

List<List<pojo>> pojoList
counter = 0;
initialise new tempList
iterate list
add current pojo to temp list
if counter = 10 then add tempList to pojoList
reset counter and tempList and continue until list is iterated

Is there an alternative solution ?

like image 483
blue-sky Avatar asked Jan 31 '13 18:01

blue-sky


2 Answers

Consider Guava's Lists.partition().

like image 168
Cyrille Ka Avatar answered Nov 16 '22 02:11

Cyrille Ka


Use sublist

List<Pojo> originalList.... //your list of POJOs  
List<List<Pojo>> pojoList = new ArrayList<List<Pojo>>(originalList/10 + 1);  
for(int i = 0; i < originalList.size(); i+=10){  
    if(i + 10 > originalList.size()){  
         pojoList.add(originalList.subList(i, originalList.size()));
    }
    else{
         pojoList.add(originalList.subList(i, i + 10));  
    }  
}
like image 1
Cratylus Avatar answered Nov 16 '22 01:11

Cratylus