Java-java8-stream-list的分页-排序
补充说明:compare的实现中,如果判断的字段是表示数字的,不管是String 还是 Integer,都转成Integer,因为Integer的compareTo方法且可以解决 1 和 10 这种String排序的问题
public static void main(String[] args) {
List<PaasUserOVo> userIdList = Lists.newArrayList();
int pageNum = 2;
int pageSize = 10;
for (int i = 0; i < 100; i++) {
PaasUserOVo userInfo = new PaasUserOVo();
userInfo.setUserId("user" + i);
userInfo.setId(i);
userInfo.setEnterpriseId("entId" + i);
UserOtherVo userOtherVo = new UserOtherVo();
userOtherVo.setCollectedNum(i);
userInfo.setUserOtherVo(userOtherVo);
userIdList.add(userInfo);
}
//分页
List<PaasUserOVo> pageList = userIdList.stream().skip((pageNum - 1) * pageSize).limit(pageSize).
collect(Collectors.toList());
//升序
pageList = pageList.stream().sorted(new Comparator<PaasUserOVo>() {
@Override
public int compare(PaasUserOVo o1, PaasUserOVo o2) {
// if (o1.getId() > o2.getId()) {
// return 1;
// }
// if (o1.getId() < o2.getId()) {
// return -1;
// }
// return 0;
// 简单的记忆为,按 o1->o2 升序,按 o2->o1 降序
return o1.getId().compareTo(o2.getId());
}
}).collect(Collectors.toList());
//降序
pageList = pageList.stream().sorted(new Comparator<PaasUserOVo>() {
@Override
public int compare(PaasUserOVo o1, PaasUserOVo o2) {
// if (o1.getId() > o2.getId()) {
// return -1;
// }
//if (o1.getId() < o2.getId()) {
// return 1;
// }
// return 0;
// 简单的记忆为,按 o1->o2 升序,按 o2->o1 降序
return o2.getId().compareTo(o1.getId());
}
}).collect(Collectors.toList());
//根据子对象userOtherVo中的collectedNum,升序排序
pageList = pageList.stream().sorted((v1, v2) -> v1.getUserOtherVo().getCollectedNum().compareTo(
v2.getUserOtherVo().getCollectedNum()
)).collect(Collectors.toList());
//原文链接:blog.csdn.net/legendaryhaha/article/details/103676823
System.out.println(pageList);
}
@Data
public class PaasUserOVo {
String enterpriseId;
String userId;
int id;
UserOtherVo userOtherVo;
}
@Data
public class UserOtherVo {
Integer collectedNum = 0;
}
正文到此结束