Alex Rivera | Logout

Split larger collection (Collections, Arrays, List) into smaller collections in Java and also keep track of last one returned

Asked 2011-03-07T16:51:43.513
20
public Collection<Comment> getCommentCollection() {
   commentCollection = movie.getCommentCollection();       
   return split((List<Comment>) commentCollection, 4);
}

public Collection<Comment> split(List<Comment> list, int size){

     int numBatches = (list.size() / size) + 1;
     Collection[] batches = new Collection[numBatches];
     Collection<Comment> set = commentCollection;

     for(int index = 0; index < numBatches; index++) {
         int count = index + 1;
         int fromIndex = Math.max(((count - 1) * size), 0);
         int toIndex = Math.min((count * size), list.size());
         batches[index] = list.subList(fromIndex, toIndex);
         set = batches[index];
     }

     return set;
 }

I am trying to split a bigger collection into smaller collections, depending on the number of items in the original collection. And then return one of the smaller collections every time the get method is called while keeping track of which smaller collection is returned. How can I achieve this?

Edit
Report

1 Answer

2

I'm not entirely sure what you're asking... do you want to remove the first 4 items from the source Collection before returning them, so that you get the next 4 the next time you call the method? If so, you could just use the Iterator:

Iterator<Comment> iter = commentCollection.iterator();
while (iter.hasNext() && group.size() < 4) {
  group.add(iter.next());
  iter.remove();
}

By doing this, though, you'd be destroying the movie object's collection of comments (unless it returns a copy of that collection each time, in which case the above wouldn't work at all). I'm guessing you're trying to do something like paging, in which case I'd suggest doing something different like partitioning a List of comments with size 4 and keeping track of a current index (the page) in that partition list.

answered 2011-03-07T17:04:59.753

Your Answer