Stream流实现分页
话不多说 直接上码
public class StreamDemo {
/**
* 实体类
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
class Person{
/** 年龄 */
private int age;
/** 性别 */
private String sex;
/** 名称 */
private String name;
}
/**
* 初始化集合
*/
public List<Person> init(){
return Stream.of(
new Person(1,"男","小明"),
new Person(2,"女","小红"),
new Person(3,"男","小李1"),
new Person(4,"女","小李2"),
new Person(5,"男","小李3"),
new Person(6,"女","小李4"),
new Person(7,"男","小李5"),
new Person(8,"女","小李6"),
new Person(9,"男","小李7"),
new Person(22,"男","小白")
).collect(Collectors.toList());
}
/**
* 分页操作
*/
public void page(Long page, Long size){
// 初始化集合
List<Person> personList = init();
personList.stream()
// 跳过多少元素,集合下标从0开始计算,需要进行处理
.skip((Math.max(1, page) -1L) * size)
// 截至到多少元素
.limit(size)
// 遍历
.forEach(System.out::println);
}
public static void main(String[] args) {
// 调用分页获取第1页数据,每页数据有3条
new StreamDemo().page(1L,3L);
// 通过[固定每页数量]遍历所有数据
int size = new StreamDemo().init().size();
int num = 0;
for (int i = 1; i <= size; i++) {
// 集合中遍历完没有数据情况
if (num >= size){
return;
}
// 分页后的数据
new StreamDemo().page((long) i,3L);
System.out.println("=== === ===");
num = i * 3;
}
}
}