下面是一个示例代码,演示如何将一个 List 集合按每4条一组拆分,并对每组中的数据进行排序:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        // 假设 list 中有一些数据
        for (int i = 1; i <= 10; i++) {
            list.add(i);
        }

        // 按每4条一组拆分
        List<List<Integer>> groups = new ArrayList<>();
        int size = list.size();
        int index = 0;
        while (index < size) {
            List<Integer> group = new ArrayList<>();
            if (index + 4 <= size) {
                group.addAll(list.subList(index, index + 4));
                index += 4;
            } else if (index + 2 <= size) {
                group.addAll(list.subList(index, index + 2));
                index += 2;
            } else {
                group.addAll(list.subList(index, size));
                index = size;
            }
            groups.add(group);
        }

        // 对每组进行排序
        for (List<Integer> group : groups) {
            Collections.sort(group);
        }

        // 输出结果
        for (List<Integer> group : groups) {
            System.out.println(group);
        }
    }
}

输出结果:

[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10]

在示例代码中,首先创建一个 List 集合并添加一些数据。然后使用 while 循环按每4条一组拆分,如果剩余数据不够4条,则取出剩余的数据。接着对每组数据进行排序,最后输出结果

java 定义一个list集合存储对象类型数据将此list按每4条一组拆分并排序1-4 若已有2条数据在一组中则将集合中数据取出2条来做分组

原文地址: https://www.cveoy.top/t/topic/h9BO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录