Stream实现List集合在内存中分页

Posted 醉酒的小男人

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Stream实现List集合在内存中分页相关的知识,希望对你有一定的参考价值。

最近开发了一个需求,定时任务从RPC加载全量数据缓存到redis中,周期性的刷新缓存中的数据。客户端调用API,通过参数key和当前页pageIndex和页大小pageSize,查询对应的页码的数据。我模拟的一下当时的代码:

package page;

public class User {
    private int id;
    private Integer age;
    private String name;

    public User(){

    }

    public User(int id, Integer age, String name) {
        this.id = id;
        this.age = age;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\\'' +
                '}';
    }
}
package page;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class PageTest {
    public static void main(String[] args) {
        String searchKey = "北京";
        Integer pageIndex = 2;
        Integer pageSize = 2;
        List<User> userList = getUserPageList(searchKey,pageIndex,pageSize);
        System.out.println(userList);
    }

    private static List<User> getUserPageList(String searchKey,Integer pageIndex,Integer pageSize) {
        List<User> userList = getUsers();
        List<User> users = userList.stream().filter(user -> user.getName().contains(searchKey)).skip((pageIndex-1)*pageSize).limit(pageSize).collect(Collectors.toList());
        return users;
    }

    private static List<User> getUsers() {
        List<User> userList = new ArrayList<>();
        userList.add(new User(1,1,"北京1"));
        userList.add(new User(2,2,"北京2"));
        userList.add(new User(3,3,"北京3"));
        userList.add(new User(4,4,"北京4"));
        userList.add(new User(5,5,"北京5"));
        userList.add(new User(6,6,"上海1"));
        userList.add(new User(7,7,"上海2"));
        userList.add(new User(8,8,"上海3"));
        userList.add(new User(9,9,"上海4"));
        userList.add(new User(10,10,"上海5"));
        userList.add(new User(11,11,"南京1"));
        userList.add(new User(12,12,"南京2"));
        userList.add(new User(13,13,"南京3"));
        userList.add(new User(14,14,"南京4"));
        userList.add(new User(15,15,"浙江1"));
        return userList;
    }
}

查询结果:

以上是关于Stream实现List集合在内存中分页的主要内容,如果未能解决你的问题,请参考以下文章

TP5报如下的错误 Indirect modification of overloaded element of thinkpaginatorCollection has no effect(代码片段

在具有自定义单元格高度的垂直 UICollectionView 上居中分页

求教jsp分页显示的问题,如何循环并分页取得参数?

jsp页面中怎样获得list

List.stream() 各方法应用

List.stream() 各方法应用