Monday, 12 July 2010

Paging algorithm

For some reasons my brain has trouble with some things. Spelling is one, another one is the algorithm for pagination - at least that's what I'm calling it. Basically it's when you've got a large result set and want to make subsets with a given max size to be processed. I recently ran into this when writing a small program to dump data to a excel spreadsheet and I found out that there is a 256 column limit.



After 10 minutes of fruitless googling I had to think for myself and write something (in java). I'm blogging my solution so that I don't have to think again. Please excuse the formatting.



public static <T> List<List<T>> page(List<T> artifacts, int pageSize) {
List<List<T>> result = new ArrayList<List<T>>();

for (int sheetNumber = 0; sheetNumber <= (artifacts.size() / pageSize); sheetNumber++) {

int fromIndex = sheetNumber * pageSize;
int toIndex = Math.min(artifacts.size(), fromIndex + pageSize);

// create a shorter view on this list
List<T> subList = artifacts.subList(fromIndex, toIndex);

result.add(subList);
}
return result;
}


No comments:

Post a Comment