import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
/**
* 对list进行分页
*/
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PageResult<T> {
private List<T> resultList;
private String next;
private long total;
/**
* 内存list分页
* 从开始遍历的话,start请输入"0"
* 当返回的next为"0"时,表示到列表的末尾
*
* @param start start
* @param limit limit
* @param list list
* @param <T> T
* @return PageResult
*/
public static <T> PageResult<T> pageList(int start, int limit, List<T> list) {
List<T> safeList = Optional.ofNullable(list).orElseGet(Lists::newArrayList);
int maxIndex = safeList.size();
int nextIndex = start + limit;
int fromIndex = Math.min(start, maxIndex);
int toIndex = Math.min(nextIndex, maxIndex);
String next = toIndex == maxIndex ? "0" : String.valueOf(nextIndex);
return PageResult.<T> builder()
.resultList(safeList.subList(fromIndex, toIndex))
.next(next)
.total(safeList.size())
.build();
}
public static void main(String[] args) {
PageResult<Integer> pageResult = PageResult.pageList(0, 2, Arrays.asList(1, 2, 3, 4, 5));
}
}
java对list进行分页
点赞
收藏