对一个链表List,进行手动分页,核心代码就是pagin函数:
import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Random; @Slf4j public class ImplementsPaging { private List<String> list; @Before public void init(){ list = new ArrayList<>(); list.add("Luo"); list.add("Tian"); list.add("yan"); list.add("23"); list.add("elegant"); list.add("optimistic"); list.add("mysterious"); list.add("classical"); } @Test public void testPaging(){ Random random = new Random(); int cursor = random.nextInt(3); int limit = random.nextInt(10); //分页之前 list.forEach(l -> log.debug(l)); //分页之后 List<String> paging = paging(cursor, limit, list); paging.forEach(l -> log.debug(l)); } public List<String> paging(int cursor, int limit, List<String> list){ log.debug("cursor={} and limit={}",cursor,limit); //手动实现分页 if (cursor < 0 || cursor >= list.size() || limit <= 0) { return null; } int lastIndex = cursor + limit; if (lastIndex > list.size()) { lastIndex = list.size(); } //获得分页后的deviceIdList list = list.subList(cursor, lastIndex); return list; } }
多次测试均能够达到正常分页效果。