项目开发中经常会遇到需要将查到的list再重新分页返回给前端的情况,基本的思路可以通过subList方法来返回数据。我看了网上几个代码,感觉这个挺好的,可以借鉴下。
原文链接:https://blog.youkuaiyun.com/difffate/article/details/71531194
import java.util.ArrayList;
import java.util.List;
/**
* Create by zxb on 2017/5/10
*/
public class SubListTest {
public static void main(String[] args) throws ClassNotFoundException {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 22; i++) {
list.add(i);
}
int pageNo = 2; //从1开始
int pageSize = 15;
int fromIndex = pageSize * (pageNo - 1);
int toIndex = pageSize * pageNo;
if (toIndex > list.size()) {
toIndex = list.size();
}
if (fromIndex > toIndex) {
fromIndex = toIndex;
}
System.out.println(fromIndex+","+toIndex); //15,22
System.out.println(list.subList(fromIndex, toIndex)); //[15, 16, 17, 18, 19, 20, 21]
}
}