1.先对List里的对象的时间字段按最近时间进行排序
1.1 流的方式,降序
List<实体类> collect = list.stream()
.sorted(Comparator.comparing(实体类::getDate).reversed()).collect(Collectors.toList());
如果想要升序排列,将.reversed()删掉
1.2 Java中Colelctions工具类为我们提供的两种集合排序方法
链接:https://blog.csdn.net/veryisjava/article/details/51675036?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522164238698916780357231112%2522%252C%2522scm%2522%253A%252220140713.130102334…%2522%257D&request_id=164238698916780357231112&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allbaidu_landing_v2~default-3-51675036.first_rank_v2_pc_rank_v29&utm_term=对List排序&spm=1018.2226.3001.4187
2.再分页
2.1先建工具类DPage
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* 对List集合进行分页
* @param <T>
*/
public class DPage<T> {
//当前页
private Integer pageNum;
//总记录数
private Integer total;
//总页数
private Integer pages;
//当前页显示多少条记录
@JsonIgnore
private Integer pageSize;
private List<T> list;
public DPage(List<T> list,Integer pageNum,Integer pageSize){
this.pageNum = pageNum;
this.pageSize = pageSize;
this.total = list.size();
//总记录数和每页显示的记录之间是否可以凑成整数(pages)
boolean full = total % pageSize == 0;
//分页 == 根据pageSize(每页显示的记录数)计算pages
if(!full){
//如果凑不成整数
this.pages = total/pageSize + 1;
}else{
//如果凑成整数
this.pages = total/pageSize;
}
int fromIndex = 0;
int toIndex = 0;
fromIndex = pageNum*pageSize-pageSize;
if(pageNum == 0){
throw new ArithmeticException("第0页无法展示");
}else if(pageNum>pages){
//如果查询的页码数大于总的页码数,list设置为[]
list = new ArrayList<>();
}else if(pageNum == pages){
//如果查询的当前页等于总页数,直接索引到total处
toIndex = total;
}else{
//如果查询的页码数小于总页数,不用担心切割List的时候toIndex索引会越界,直接等
toIndex = pageNum*pageSize;
}
if(list.size() == 0){
this.list = list;
}else{
this.list = list.subList(fromIndex, toIndex);
}
}
public Integer getPageNum() {
return pageNum;
}
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public Integer getPages() {
return pages;
}
public void setPages(Integer pages) {
this.pages = pages;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
}
2.2分页,前端传来的数据用实体类接收,接收时加上current,size字段
DPage<实体类> dPage=new DPage<>(collect,接收前端数据的实体类.getCurrent(),接收前端数据的实体类.getSize());