开发者

List (ArrayList)Traversal in java

example, suppose I have one list whi开发者_StackOverflow社区ch contains 45 element so from which i need to create sets of lists which contains 10 element means if main list has 45 elements then it will crate 4 sets of 10 elements and and 1 for 5 elements so finally I wil get 5 lists. ok so after creating lists i need to call one function. that function will called 5 times.

1 set
call()
2 set
call()
3 set
call()

4 set call()

5 set call()

can anyone please provide the solution..

Thanks in advance vinod


Build upon the answer from Deepak:

If you have a List<?> list and want to call function call with size 10 chunks you may use the following code:

for (int idx = 0; idx < list.size(); idx += 10) {
    List<?> subList = list.subList(idx, Math.min(list.size(), idx + 10));
    call(subList);
}


list.subList() function in java should do the trick


Guava has just the method for you:

Iterables.partition(Iterable<E>, size)

Sample usage:

List<String> list = // initialize List
for(List<String> subList : Iterables.partition(list, 10)){
    // do something with the list
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜