java代码 数据较大的list 进行分页的一个方法,并且调用测试
时间: 2024-03-17 14:45:35 浏览: 56
对数据进行分页显示到table中的实现方法
以下是Java代码实现数据较大的List分页的方法:
```java
import java.util.List;
public class ListPager<T> {
private List<T> data;
private int pageSize;
public ListPager(List<T> data, int pageSize) {
this.data = data;
this.pageSize = pageSize;
}
public List<T> getPage(int pageNumber) {
int fromIndex = (pageNumber - 1) * pageSize;
if (fromIndex >= data.size()) {
return null;
}
int toIndex = Math.min(fromIndex + pageSize, data.size());
return data.subList(fromIndex, toIndex);
}
}
```
使用示例:
```java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Mock data
List<String> data = new ArrayList<>();
for (int i = 1; i <= 100; i++) {
data.add("Item " + i);
}
// Create pager
ListPager<String> pager = new ListPager<>(data, 10);
// Get page 1
List<String> page1 = pager.getPage(1);
System.out.println("Page 1: " + page1);
// Get page 2
List<String> page2 = pager.getPage(2);
System.out.println("Page 2: " + page2);
// Get page 3
List<String> page3 = pager.getPage(3);
System.out.println("Page 3: " + page3);
}
}
```
输出结果:
```
Page 1: [Item 1, Item 2, Item 3, Item 4, Item 5, Item 6, Item 7, Item 8, Item 9, Item 10]
Page 2: [Item 11, Item 12, Item 13, Item 14, Item 15, Item 16, Item 17, Item 18, Item 19, Item 20]
Page 3: [Item 21, Item 22, Item 23, Item 24, Item 25, Item 26, Item 27, Item 28, Item 29, Item 30]
```
阅读全文