Java: design pattern for paged results

So, Iterable and Iterator and List . What do you use if you are trying to provide an interface for other Java code to encapsulate the functionality provided by a remote service that returns results on "pages"?

As an example, consider a database or a web page (for example, the flickr API ). After the first search for results, you know the total number of results and the first results N, but you do not know the remaining results until you get the rest.

+7
source share
3 answers

In my application, I decided to implement Iterator<ListPage> , where the iterator next() implementation is to load the next page of results, and ListPage are methods that return a real list and metadata, such as the total number of results, # per page, page # and total pages:

 public interface ListPage<T> { public List<T> getList(); public int getTotal(); public int getPage(); public int getPages(); public int getPerPage(); } 
0
source

In your case, given that each item is expensive to extract, it probably makes sense to accept aggregated results and not iterate over directly for each item when removing the call level.

You can provide one method that returns a list similar to this:

 List<YourClass> getResults(int offset, int maxResults) 

where offset will be the index of the first element you want to start with, and maxresults is the maximum number of elements you want to have in the list. Then you can iterate over the list to display on your page.

The Java Persistence API also follows the same pattern, the query interface provides 3 methods that do the above:

 setFirstResult() setMaxResults() List getResultList() 

http://download.oracle.com/javaee/5/api/javax/persistence/Query.html

+4
source

I will remain compatible with the Iterator interface and will not introduce new methods (as suggested above). Instead, I would use lazy loading in hasElements() , nextElement() and your class recipients.

+2
source

All Articles