Java集合分组按页数查找

75 阅读1分钟
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
        int groupSize = 3;
        int pageNumber = 2;

        int startIndex = (pageNumber - 1) * groupSize;
        int endIndex = Math.min(startIndex + groupSize, list.size());
        List<Integer> subList = list.subList(startIndex, endIndex);
        // 遍历当前页的组
        for (Integer num : subList) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}

查出的结果 ``` 4 5 6

若获取总共分了多少组

import java.util.List;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
        int groupSize = 3;
        
        int totalGroups = (int) Math.ceil((double) list.size() / groupSize);
        
        System.out.println("Total groups: " + totalGroups);
    }
}

结果:``` Total groups: 5