對一個鏈表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; } }

多次測試均能夠達到正常分頁效果。
