vinod
vinod

Reputation: 1202

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

Upvotes: 1

Views: 637

Answers (3)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298878

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
}

Upvotes: 1

Howard
Howard

Reputation: 39197

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);
}

Upvotes: 2

Deepak
Deepak

Reputation: 2102

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

Upvotes: 1

Related Questions