分页工具类,一般请求参数会有第几页和每页大小,返回值也会把对应的参数传递回去,其他的参数还有数据的总页数和总数,这样使用方就可以更根据这两个参数判断出是否还有下一页以及显示多少页,集合数据代表这次请求所需要的数据,其他数据可以存储一些汇总信息。
@Setter@Getterpublic class Pagination<T> implements Serializable {// 第几页private int page;// 每页大小private int pageSize;// 总页数private int totalPage;// 总数private int totalCount;// 集合数据private Collection<T> list;// 其他数据private Map<String, Object> other;public Pagination() {}public Pagination(int page, int pageSize, int totalPage, int totalCount, Collection<T> list) {this.page = page;this.pageSize = pageSize;this.totalPage = totalPage;this.totalCount = totalCount;this.list = list;}/*** 获取分页结果* @param page 第几页* @param pageSize 每页大小* @param supplier 获取总页数* @param biFunction 获取结果数据,参数分别是偏移量,数量,以及返回的结果集合* @param <T> vo类型* @return 分页bean*/public static <T> Pagination<T> get(int page, int pageSize, Supplier<Integer> supplier, BiFunction<Integer, Integer, Collection<T>> biFunction) {pageSize = handlePageSize(pageSize);int totalCount = supplier.get();Collection<T> list = null;if (totalCount > 0) {list = biFunction.apply(page > 0 ? (page - 1) * pageSize : 0, pageSize);}return new Pagination<>(page, pageSize, (int) Math.ceil((double) totalCount / pageSize), totalCount, list == null ? Collections.<T>emptyList() : list);}public static <T> Pagination<T> getEmpty(int page, int pageSize) {return new Pagination<>(page, pageSize, 0, 0, Collections.<T>emptyList());}public static int handlePageSize(int pageSize) {return Math.min(pageSize, 100);}}
组装Map,不用计算大小设置,不用先new再put
public class MapUtil {public static Map<String, Object> get(Object... objects) {if (objects == null || objects.length < 2 || objects.length % 2 != 0) {throw new RuntimeException("参数数量不对");}Map<String, Object> result = new LinkedHashMap<>(objects.length / 2, 1);for (int i = 0; i < objects.length; i = i + 2) {result.put(String.valueOf(objects[i]), objects[i + 1]);}return result;}}
版权声明:本文为ph3636原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。