Convert a list to a list of lists containing 10 items

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

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?

+7
source share
3 answers

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)); } } 
+1
source

Consider Guava Lists.partition () .

+4
source

Perhaps you can use subList .

You still need to repeat, but you don't need to create a tempList

0
source

All Articles