简体   繁体   中英

List (ArrayList)Traversal in java

example, suppose I have one list which 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);
}

java中的list.subList()函数应该可以搞定

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM