1. 程式人生 > >java list手動分頁

java list手動分頁

package Test;

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

/**
 * 
 * @author csz
 * @date 2018-02-05
 */
public class ListPageUtil {
	/**
	 * 
	 * @param page
	 *            當前頁數
	 * @param pageSize
	 *            每頁得大小
	 * @param list
	 *            分頁的物件
	 * @return
	 */
	private static List<Integer> getListPage(int page, int pageSize, List<Integer> list) {
		if (list == null || list.size() == 0) {
			throw new RuntimeException("分頁資料不能為空!");
		}
		
		int totalCount = list.size();
		page = page - 1;
		int fromIndex = page * pageSize;
		//分頁不能大於總數
	    if(fromIndex>=totalCount) {
	    	throw new RuntimeException("頁數或分頁大小不正確!");
		}
		int toIndex = ((page + 1) * pageSize);
		if (toIndex > totalCount) {
			toIndex = totalCount;
		}
		return list.subList(fromIndex, toIndex);

	}

	public static void main(String[] args) {
		// 構造100條資料
		List<Integer> list = new ArrayList<Integer>();
		for (Integer i = 1; i <= 100; i++) {
			list.add(i);
		}

		int page = 1;// 第一頁
		int pageSize = 10;// 每頁10條

		List<Integer> listPage = getListPage(page, pageSize, list);
		System.out.println("第" + page + "頁");
		for (Integer integer : listPage) {
			System.out.println(integer);
		}

		// 測試第10頁
		page = 10;
		listPage = getListPage(page, pageSize, list);
		System.out.println("第" + page + "頁");
		for (Integer integer : listPage) {
			System.out.println(integer);
		}

		// 測試第11頁
		page = 11;
		listPage = getListPage(page, pageSize, list);
		System.out.println("第" + page + "頁");
		for (Integer integer : listPage) {
			System.out.println(integer);
		}

	}
}


返回結果:

第1頁
1
2
3
4
5
6
7
8
9
10
第10頁
91
92
93
94
95
96
97
98
99
100
Exception in thread "main" java.lang.RuntimeException: 頁數或分頁大小不正確!
	at Test.ListPageTest.getListPage(ListPageTest.java:27)
	at Test.ListPageTest.main(ListPageTest.java:64)