前言
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;
/**
* List集合流排序分页
*
* @author tuojinhui
* @date 2019-09-11
*/
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());
/**
* 方法描述:排序分页
*
* @param records 源记录
*/
public <T> SortPage<T> setRecords(List<T> records){
return new SortPage<>(records);
}
public static class SortPage<T> {
private List<T> records;
public SortPage(List<T> records) {
this.records = records;
}
/**
* 方法描述:集合排序(升序)
*
* @return java.util.List<T>
*/
@SafeVarargs
public final <U extends Comparable<?>> SortPage<T> sortByAsc(Function<? super T, ? extends U> ...functions){
if (Objects.isNull(records) || Objects.isNull(functions)) {
return this;
}
Comparator<T> 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;
}
/**
* 方法描述:集合排序 (降序)
*
* @return java.util.List<T>
*/
@SafeVarargs
public final <U extends Comparable<?>> SortPage<T> sortByDesc(Function<? super T, ? extends U> ...functions){
if (Objects.isNull(records) || Objects.isNull(functions)) {
return this;
}
Comparator<T> 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;
}
/**
* 方法描述:集合排序 (自定义排序)
*
* @return java.util.List<T>
*/
public final SortPage<T> sort(Comparator<? super T> comparator){
if (Objects.isNull(records) || Objects.isNull(comparator)) {
return this;
}
records = records.stream().sorted(comparator).collect(Collectors.toList());
return this;
}
/**
* 方法描述:集合分页
*
* @return java.util.List<T>
*/
public SortPage<T> 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;
}
/**
* 方法描述:收集
*
* @return java.util.List<T>
*/
public List<T> collect() {
return records;
}
}
}