先科普一下什么是蛇形分组吧!
蛇形分组的意思就是数据按照蛇形S的方式进行展示
处理的结果按照上图处理数据
数据分组一样的随机处理,所以我这里没有做展示
下面就是根据班级进行蛇形分组的方法展示
/**
* 模拟数据,自动式按照大到小排序,DESC
**/
private static List data(Integer maxSource, Integer size){
List soucreList = new ArrayList<>(size);
for(int i=0;i<size;i++){
soucreList.add(maxSource-i);
}
return soucreList;
}
/**
* checkBool -> true 开启蛇形分组,false 不开启蛇形分组
* sourceDatas -> 模拟的数据集合,需要分组的集合
* pageSize -> 需要分组的数量,也就是说,多少pageSize一组
**/
public static List<List> groupByList(List sourceDatas,Integer pageSize,Boolean checkBool){
// 分组集合
List<List> groupLists = new ArrayList();
// 分组数据
List tempDataList = new ArrayList(pageSize);
Integer index = 0;
if(Objects.nonNull(sourceDatas) && pageSize > 0){
for (int i = 0; i < sourceDatas.size(); i++) {
if (i != 0 && i % pageSize == 0) {
if (!tempDataList.isEmpty()) {
// 分组倒序
if(checkBool && index % 2 != 0){
// 这里是第二个开始蛇皮分组,所以这个地方是取余2
Collections.reverse(tempDataList);
groupLists.add(tempDataList);
} else {
groupLists.add(tempDataList);
}
}
tempDataList=new ArrayList();
index ++;
}
tempDataList.add(sourceDatas.get(i));
}
}
if (!tempDataList.isEmpty()) {
Integer size = tempDataList.size();
if(checkBool && size != pageSize){
for (int i=0,length=pageSize-size;i<length;i++){
// 不足数据用null补充,保证每一个集合都是pageSize的数量和size
tempDataList.add(size+i,null);
}
}
if(checkBool && index % 2 != 0){
// 判断最后一个集合是不是倒序蛇形分组的集合
Collections.reverse(tempDataList);
}
groupLists.add(tempDataList);
}
return groupLists;
}
public static void main(String[] args) {
// 根据班级进行分组
//班级数量
Integer classSize = 4;
// 最大分数
Integer maxSource = 100;
// 模拟人数
Integer size = 14;
// 是否是蛇形分组
Boolean checkBool = true;
List<List> list = groupByList(data(maxSource,size), classSize, checkBool);
out.println("根据pageSize分组后数据:");
list.forEach(l -> out.println(l));
Integer listSize = list.size();
List<List> classList = new ArrayList<>(listSize);
for(int i=0;i<classSize;i++){
// 班级循环获取蛇形成绩用户
classList.add(getGroupList(list, i));
}
out.println("蛇形分组后数据:");
classList.forEach(classL->out.println(classL));
}
/**
* list -> 蛇形分组后的集合,数据
* [100, 99, 98, 97]
* [93, 94, 95, 96]
* [92, 91, 90, 89]
* [null, null, 87, 88]
* classNum -> 是需要分成几个组,来组成蛇形
*/
private static List getGroupList(List<List> list, Integer classNum){
Integer size = list.size();
List classList = new ArrayList();
for(int i=0;i<size;i++){
List groupClassList = list.get(i);
if(Objects.nonNull(groupClassList.get(classNum))){
classList.add(groupClassList.get(classNum));
}
}
return classList;
}
处理结果数据后
根据pageSize分组后数据:
[100, 99, 98, 97]
[93, 94, 95, 96]
[92, 91, 90, 89]
[null, null, 87, 88]
蛇形分组后数据
A班级:[100, 93, 92]
B班级:[99, 94, 91]
C班级:[98, 95, 90, 87]
D班级:[97, 96, 89, 88]
有什么问题欢迎补充,不懂的可以留言哦!
点个关注不迷路!