代码中注释了很清楚,也很直观,需要三个参数,分别是要截取的list集合,当前页,每页条数,具体代码如下:
package com.rocky.fintech.boss.util;
import java.util.ArrayList;
import java.util.List;
/**
* @author 9043
* @description:对集合分页
* @date 2019/12/14 10:17
*/
public class ListPagingUtil {
/**
*
* @param list
* @param pageNum
* @param pageSize
* @param <T>
* @return 返回当前页数据
*/
public static <T> List<T> getListPaging(List<T> list, int pageNum, int pageSize) {
if(list == null || list.size() <= 0){
return new ArrayList<>(0);
}
//开始下标
int startIndex = (pageNum - 1) * pageSize;
//结束下标 subList()方法不包含结束下标的元素
int endIndex = pageNum * pageSize;
//list总条数
int total = list.size();
//总页数
int pageCount = 0;
//通过取余决定是否给总页数加1
int num = total % pageSize;
if (num == 0) {
pageCount = total / pageSize;
} else {
pageCount = total / pageSize + 1;
}
//如果当前页是最后一页的话 要包含集合的最后一条数据,因为sublist方法本身结束的下标是不包含当前元素的
if (pageNum == pageCount) {
endIndex = total;
}
return list.subList(startIndex, endIndex);
}
}
以下代码仅供参考,使用了分页插件:
@Override
public PageDTO<PartnerScheduleBO> getPartnerScheduleList(int pageNum, int pageSize
, PartnerScheduleTrackQuery partnerScheduleTrackQuery) {
List<PartnerScheduleBO> partnerScheduleBOS = new ArrayList<>();
List<PartnerBO> partners = this.partnerScheduleTrackMapper.findPartnerScheduleTrackListByPartnerScheduleTrackQuery(partnerScheduleTrackQuery);
partners.forEach(partnerBO -> {
PartnerScheduleBO partnerScheduleBO = new PartnerScheduleBO();
partnerScheduleBO.setId(partnerBO.getId());
partnerScheduleBO.setPartnerNo(partnerBO.getPartnerNo());
partnerScheduleBO.setPartnerName(partnerBO.getPartnerName());
partnerScheduleBO.setStage(partnerBO.getStage());
partnerScheduleBO.setAppScheduleStage(partnerBO.getAppScheduleStage());
partnerScheduleBO.setTrackerAdminId(partnerBO.getTrackerAdminId());
partnerScheduleBO.setAppScheduleAddTime(partnerBO.getAppScheduleAddTime());
partnerScheduleBO.setRemark(partnerBO.getRemark());
List<ScheduleTrackBO> scheduleTrackBOS = partnerBO.getScheduleTrackBOS();
if (!CollectionUtils.isEmpty(scheduleTrackBOS)) {
partnerScheduleBO.setPlanTimeStart(scheduleTrackBOS.get(0).getPlanTimeStart());
partnerScheduleBO.setPlanTimeEnd(scheduleTrackBOS.get(scheduleTrackBOS.size() - 1).getPlanTimeEnd());
}
partnerScheduleBOS.add(partnerScheduleBO);
});
PageDTO<PartnerScheduleBO> pageDTO = new PageDTO<>();
pageDTO.setList(ListPagingUtil.getListPaging(partnerScheduleBOS, pageNum, pageSize));
pageDTO.setPageNum(pageNum);
pageDTO.setPageSize(pageSize);
pageDTO.setTotal(Long.valueOf(partners.size()));
return pageDTO;
}
如有疑问请留言。