Tuesday, October 1, 2013

Grails pagination on a ArrayList

In my recent grails project, i needed to paginate on an array list, so I wrote a function and thought would share it with you all.

public List getFilteredList(int max, int offset) {
    max = Math.min(max ?: 25, 100)
    offset = (offset && offset > 0) ?: 0

    List names = getNames() //Loads the complete list
    int total = names.size()
    int upperLimit = findUpperIndex(offset, max, total)
    List filteredNames = names.getAt(offset..upperLimit)
    return filteredNames
}

private static int findUpperIndex(int offset, int max, int total) {
    max = offset + max - 1
    if (max >= total) {
        max -= max - total + 1
    }
    return max
}
So now if offset=20 and max=10, total = 28 so this will generate a list from 21st to 28th elements of the main list.

No comments:

Post a Comment