com.ideaaedi.commonds.rank.Ranker Maven / Gradle / Ivy
The newest version!
package com.ideaaedi.commonds.rank;
import com.ideaaedi.commonds.sort.DefaultSortSupporter;
import com.ideaaedi.commonds.sort.SortStrategy;
import com.ideaaedi.commonds.sort.SortSupporter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* 排名器
*
* P.S. 这是稳定的
*
* @author JustryDeng
* @since 1.0.0
*/
public class Ranker> {
private final SortSupporter sortSupporter;
private final RankSupporter rankSupporter;
private Ranker(SortSupporter sortSupporter, DefaultRankSupporter rankSupporter) {
this.sortSupporter = sortSupporter;
this.rankSupporter = rankSupporter;
}
public static > Ranker defaultInstance(){
return new Ranker<>(new DefaultSortSupporter(), new DefaultRankSupporter());
}
public static > Ranker buildInstance(SortSupporter sortSupporter, DefaultRankSupporter rankSupporter){
return new Ranker<>(new DefaultSortSupporter(), new DefaultRankSupporter());
}
/**
* @see Ranker#generateRankingList(Collection, boolean, SortStrategy, RankStrategy)
*/
public List generateRankingList(Collection dataList, boolean asc) {
return this.generateRankingList(dataList, asc, SortStrategy.AUTO, RankStrategy.INDEX_POSTPONED_IF_SAME);
}
/**
* 排序
*
* @param dataList
* 要被排名的数据集
* @param asc
* true-正向, false-反向
* @param sortStrategy
* 排序策略
* @param rankStrategy
* 排名策略
*
* @return 排序后的数据
*/
public List generateRankingList(Collection dataList, boolean asc, SortStrategy sortStrategy, RankStrategy rankStrategy) {
// -> 数据整理
if (dataList == null || dataList.size() == 0) {
return new ArrayList<>();
}
List nullList = new ArrayList<>(16);
List nonNullList = new ArrayList<>(16);
dataList.forEach(x -> {
if (x == null) {
nullList.add(null);
} else {
nonNullList.add(x);
}
}
);
if (nonNullList.size() == 0) {
return nullList;
}
// -> 排序
List nonNullSortedList = sortSupporter.doSort(nonNullList, sortStrategy, asc);
// -> 排名
List sortedAndRankedList = rankSupporter.doRank(nonNullSortedList, rankStrategy);
// 将null元素, 放置在最后
sortedAndRankedList.addAll(nullList);
return sortedAndRankedList;
}
}