-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
41 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package com.oing.util; | ||
|
||
import com.oing.domain.PaginationDTO; | ||
|
||
import java.util.Collections; | ||
import java.util.List; | ||
|
||
public class Paginator<T> { | ||
private final List<T> items; | ||
private final int pageSize; | ||
|
||
public Paginator(List<T> items, int pageSize) { | ||
if (pageSize <= 0) { | ||
throw new IllegalArgumentException("Page size must be greater than 0."); | ||
} | ||
this.items = items != null ? items : Collections.emptyList(); | ||
this.pageSize = pageSize; | ||
} | ||
|
||
public PaginationDTO<T> getPage(int pageNumber) { | ||
if (pageNumber <= 0) { | ||
throw new IllegalArgumentException("Page number must be greater than 0."); | ||
} | ||
|
||
int totalItems = items.size(); | ||
int totalPages = (int) Math.ceil((double) totalItems / pageSize); | ||
|
||
if (pageNumber > totalPages) { | ||
return new PaginationDTO<>(totalPages, Collections.emptyList()); | ||
} | ||
|
||
int startIndex = (pageNumber - 1) * pageSize; | ||
int endIndex = Math.min(startIndex + pageSize, totalItems); | ||
|
||
List<T> pageItems = items.subList(startIndex, endIndex); | ||
return new PaginationDTO<>(totalPages, pageItems); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters