JAVA8 分页工具

使用JAVA8的API可以实现分页,在数据量相对稳定的情况下,可以查出所有数据,配合缓存使用

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @version 1.0
 * @author levelmini
 * @param <T>
 */
public class Page<T> {
	private int current_page;
	private int size;
	private int total_page; 
	private int total_sum;
	private transient List<T> instanceList;//Gson不序列化transient字段
	private List<T> currentPageData;
	private transient Optional<List<T>> op;
	
	public Page(List<T> instanceList,int size) {
		this.size = size;
		setInstanceList(instanceList);
	}
	
	public int getCurrent_page() {
		return current_page;
	}
	public void setCurrent_page(int current_page) {
		this.current_page = current_page<1?1:current_page>this.total_page?this.total_page:current_page;
		setCurrentPageData(currentPageData());
	}
	public int getSize() {
		return size;
	}
	public void setSize(int size) {
		this.size = size;
	}
	public int getTotal_page() {
		return total_page;
	}
	public int getTotal_sum() {
		return total_sum;
	}
	public List<T> getInstanceList() {
		return instanceList;
	}
	public void setInstanceList(List<T> instanceList) {
		this.op= Optional.ofNullable(instanceList);
		this.instanceList = op.orElse(new ArrayList<T>());
		this.total_sum = this.instanceList.size();
		this.total_page =(int) Math.ceil(1.0*this.total_sum/this.size);
	}
	public void setCurrentPageData(List<T> currentPageData) {
		this.currentPageData = currentPageData;
	}
	public List<T> getCurrentPageData(){
		return this.currentPageData;
	}
	private List<T> currentPageData(){
		if(this.size==0 || this.total_page == 1){
			return this.instanceList;
		}
		List<T> currentPageData = new ArrayList<T>();
		instanceList.stream().skip((this.current_page-1)*this.size).limit(this.size).forEach(e->currentPageData.add(e));
		return currentPageData;
	}
}

用法:

List<News> newsList = newsService.findAll();
Page<News> page = new Page<>(newsList, size);
page.setCurrent_page(current_page);
return JsonUtil.toJson(page,"yyyy-MM-dd");


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值