Mohammed Shirhaan
Mohammed Shirhaan

Reputation: 553

How to convert a list of objects to Page using subList when the size of list is less than Page Offset?

This is the simplified code

public Page<TestResource> getTestData(TestData testData, Pageable pageRequest) {

List<TestResource> results = getSomething(testData);
        int start = (int) pageRequest.getOffset();
        int end = (start + pageRequest.getPageSize()) > results.size() ? results.size()
        : (start + pageRequest.getPageSize());
        return new PageImpl<DemographicsAuditsResource>(results.subList(start, end), pageRequest, results.size());

When the number of records in results is less, say 1, and if my page offset is greater than 1 say 6, then I get java.lang.IllegalArgumentException: fromIndex(6) > toIndex(1), because of this line

results.subList(start, end)

Since end is less than start. How can I generate the sublist when result set is less?

Upvotes: 0

Views: 327

Answers (1)

Amit Phaltankar
Amit Phaltankar

Reputation: 3424

If you are building a web service - having start greater than actual result size is a 40 NOT FOUND condition.

Do the below check and throw exception and map it to 404 otherwise return an empty list or null (take your call)

if(start >= results){
   return new Arrayalist<TestResource>(); // or throw exception
}

Upvotes: 1

Related Questions