Basic Chunked List Iterator

Here’s a simple chunked iterator I wrote up that makes it easy to provide list data in chunks. This is useful when there is a need to break up and process large lists in pieces/chunks

    private static class ChunkList
            implements Iterable<List> {
        private final List list;
        private final int chunkSize;
        int cur;
        boolean hasNext = true;

        public ChunkList(List list, int chunkSize) {
            this.list = list;
            this.chunkSize = chunkSize;
            this.cur = 0;
        }

        @Override
        public Iterator<List> iterator() {
            return new Iterator<List>() {
                @Override
                public boolean hasNext() {
                    return hasNext;
                }

                @Override
                public List next() {
                    int start = cur;
                    int end = cur+chunkSize;
                    if (cur+chunkSize >= list.size()) {
                        end = list.size();
                        hasNext = false;
                    }

                    List subList =  list.subList(start, end);
                    cur = end;

                    return subList;
                }

                @Override
                public void remove() {
                    throw new UnsupportedOperationException("Chunk Removal not supported");
                }
            };
        }
    }

Test driver

    public static void main(String arg[]) {
        List list = new ArrayList();
        for (int i = 1; i             list.add(i);
        }

        ChunkList chunkList = new ChunkList(list, 10);

        Iterator<List> iter = chunkList.iterator();

        while (iter.hasNext()) {
            List chunk = iter.next();
            System.err.println("#### " + chunk);
        }
    }

Results

#### [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#### [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
#### [21, 22, 23, 24]

Another (perhaps cleaner) alternative would have been to use a list iterator to “collect” elements withing the next() methods instead of employing sublist(…).

Enjoy.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s