반응형
DB에서 조회한 결과값을 페이지별로 가져오기 위하여 아래와 같이 메소드는 사용할 수 있습니다.
/**
* returns a view (not a new list) of the sourceList for the
* range based on page and pageSize
* @param sourceList
* @param page, page number should start from 1
* @param pageSize
* @return
* custom error can be given instead of returning emptyList
*/
public static <T> List<T> getPage(List<T> sourceList, int page, int pageSize) {
if(pageSize <= 0 || page <= 0) {
throw new IllegalArgumentException("invalid page size: " + pageSize);
}
int fromIndex = (page - 1) * pageSize;
if(sourceList == null || sourceList.size() <= fromIndex){
return Collections.emptyList();
}
// toIndex exclusive
return sourceList.subList(fromIndex, Math.min(fromIndex + pageSize, sourceList.size()));
}
혹여 Collection으로 사용하는 경우를 대비하여 추가해봤습니다.
public static <T> Collection<T> getPage(Collection<T> sourceList, int pageNum, int pageSize) {
if (sourceList == null) {
return Collections.emptyList();
}
List<T> list = new ArrayList<T>(sourceList);
if (pageSize <= 0 || pageSize > list.size())
pageSize = list.size();
return list.subList(pageNum * pageSize, Math.min(++pageNum * pageSize, list.size()));
}
전체 페이지를 알고자 getPageTotal도 추가해봤습니다.
public static <T> int getPageTotal(List<T> sourceList, int pageSize) {
if(pageSize <= 0) {
throw new IllegalArgumentException("invalid page size: " + pageSize);
}
// toIndex exclusive
int numPages = (int) Math.ceil((double)sourceList.size() / (double)pageSize);
return numPages;
}
반응형
'Framework > Spring Boot' 카테고리의 다른 글
[Spring boot] JAVA List 페이지처리. (0) | 2023.10.06 |
---|---|
[Spring boot] JAVA Collection List 페이징처리. (0) | 2023.10.04 |
[Spring Boot] Email 주소 검증. (0) | 2023.09.29 |