- 前言
- 代码展示
Java List集合假排序分页
我们在进行项目开发的时候可能会遇到一些获取屏幕宽度,dp px的相互转换等问题,我们当然不能每用一次就复制粘贴一次。这时候就需要一个利器-工具类。 这个工具类包含了我们一些公用的方法,只需要一句话我们就可以拿到想要的结果,既精简了我们的代码又省下了我们宝贵的时间。同时,一个好的软件工程师,万能的工具类便是他的护身法宝。(本段引用自:Android 项目开发必备-Utils类的建立与使用)
代码展示package com.common;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
public class SortPageBuilder {
@SuppressWarnings("all")
private static final Comparator super Comparable> NATURAL_COMPARATOR = Comparator.nullsLast(Comparator.naturalOrder());
@SuppressWarnings("all")
private static final Comparator super Comparable> REVERSE_COMPARATOR = Comparator.nullsLast(Comparator.reverseOrder());
public SortPage setRecords(List records){
return new SortPage<>(records);
}
public static class SortPage {
private List records;
public SortPage(List records) {
this.records = records;
}
@SafeVarargs
public final > SortPage sortByAsc(Function super T, ? extends U> ...functions){
if (Objects.isNull(records) || Objects.isNull(functions)) {
return this;
}
Comparator comparator = Comparator.comparing(functions[0], NATURAL_COMPARATOR);
for (Function super T, ? extends U> function : functions) {
if (!Objects.equals(function, functions[0])){
comparator.thenComparing(function, NATURAL_COMPARATOR);
}
}
records = records.stream().sorted(comparator).collect(Collectors.toList());
return this;
}
@SafeVarargs
public final > SortPage sortByDesc(Function super T, ? extends U> ...functions){
if (Objects.isNull(records) || Objects.isNull(functions)) {
return this;
}
Comparator comparator = Comparator.comparing(functions[0], REVERSE_COMPARATOR);
for (Function super T, ? extends U> function : functions) {
if (!Objects.equals(function, functions[0])){
comparator.thenComparing(function, REVERSE_COMPARATOR);
}
}
records = records.stream().sorted(comparator).collect(Collectors.toList());
return this;
}
public final SortPage sort(Comparator super T> comparator){
if (Objects.isNull(records) || Objects.isNull(comparator)) {
return this;
}
records = records.stream().sorted(comparator).collect(Collectors.toList());
return this;
}
public SortPage page(Long page, Long limit) {
if (Objects.isNull(records) || Objects.isNull(page) || Objects.isNull(limit)) {
return this;
}
records = records.parallelStream().skip((page - 1) * limit).limit(limit).collect(Collectors.toList());
return this;
}
public List collect() {
return records;
}
}
}



