1、使用apache工具进行手动分页
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections4.ListUtils;
import com.alibaba.fastjson.JSON;
/**
* 手动分页
* @author 张林强
*/
public class Test {
//*1 使用apache工具进行手动分页
public static void getPageContentByApache(int pageNo,int pageSize) {
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
list.add("f");
list.add("g");
List<List<String>> partition = ListUtils.partition(list, pageSize);
if(list.size()<(pageNo*pageSize)){
System.out.println("越界");
}else{
System.out.println(JSON.toJSONString(partition.get(pageNo-1)));
}
}
public static void main(String[] args) {
getPageContentByApache(3,2);
}
}
2、使用原生 Java api 进行手动分页
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections4.ListUtils;
import com.alibaba.fastjson.JSON;
/**
* 手动分页
* @author 张林强
*/
public class Test {
//*2 使用原生 Java api 进行手动分页
public static void getPageContentByApi(int pageNo,int pageSize){
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
list.add("f");
list.add("g");
//总记录数
int total = list.size();
// 开始索引
int fromIndex = (pageNo-1) * pageSize;
// 结束索引
int toIndex = fromIndex + pageSize;
// 如果结束索引大于集合的最大索引,那么规定结束索引=集合大小
if(toIndex > total){
toIndex = total;
}
if(fromIndex <= total){
List<String> subList = list.subList(fromIndex, toIndex);
System.out.println(JSON.toJSONString(subList));
}
}
public static void main(String[] args) {
getPageContentByApi(3,2);
}
}