固定子列表计数但 Java 中的动态成员 [英] Fixed SubList Count but Dynamic Members in Java

查看:41
本文介绍了固定子列表计数但 Java 中的动态成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下整数列表

List<Integer> arrayList = new ArrayList<Integer>();
   for (int i = 0; i < 7; i++) {
    arrayList.add(i);
}

所以列表是这样的[0,1,2,3,4,5,6].我的场景是

So the list is like this [0,1,2,3,4,5,6]. My scenario is

如果我将 value = 5 作为参数,那么我想像这样拆分 5 个子列表

If I give the value = 5 as parameter then I would like to split 5 sub list like this

[0,5], [1,6] , [2], [3], [4]

如果我将 value = 4 作为参数,那么我想像这样拆分 4 个子列表

If I give the value = 4 as parameter then I would like to split 4 sub list like this

[0,4], [1,5], [2,6] , [3]

如果我将 value = 3 作为参数,那么我想像这样拆分 3 个子列表

If I give the value = 3 as parameter then I would like to split 3 sub list like this

[0,3,6], [1,4], [2,5]

我已经使用以下功能进行了测试,但这不是我的需要.

I already tested with below function but it is not my need.

public List<List<Integer>> chopped(List<Integer> list, final int splitCount) {
        List<List<Integer>> parts = new ArrayList<List<Integer>>();
        final int N = list.size();
        for (int i = 0; i < N; i += splitCount) {
            parts.add(new ArrayList<Notification>(list.subList(i, Math.min(N, i + splitCount))));
        }
        return parts;
    }

在上面的函数中,我将 splitCount 赋给 5 然后函数返回

At the above function, I give splitCount to 5 then the function returns

[0,1,2,3,4], [5,6]

我期望的结果是 [0,5], [1,6] , [2], [3], [4]

推荐答案

怎么样:

public List<List<Integer>> chopped(List<Integer> list, final int splitCount) {
    List<List<Integer>> parts = new ArrayList<>(splitCount);
    for (int i = 0; i < splitCount; ++i) {
        parts.add(new ArrayList<>());
    }
    final int N = list.size();
    for (int i = 0; i < N; ++i) {
        parts.get(i % splitCount).add(list.get(i));
    }
    return parts;
}

这篇关于固定子列表计数但 Java 中的动态成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆