指点成金-最美分享吧

登录

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

佚名 举报

篇首语:本文由小编为大家整理,主要介绍了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集合在内存中分页的主要内容,如果未能解决你的问题,请参考以下文章