Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split list into "maximum" equal size chunks

Tags:

java

list

split

I have a list of non-rated items and I want them to be splitted into 5 folds. Currently, I have done as I just try to evenly split into chunks and the last one is so called "extended" chunk and this causes problems for me.

When I have nonRatedItems = {1,2,3,4,5,6,7,8}, then the chunks are:

1
2
3
4
5 6 7 8

I want to avoid this so that the output is:

1 6
2 7
3 8
4
5

Current source:

    Collections.shuffle(nonRatedItems);
    nonRatedItems = nonRatedItems.subList(0, (int) Math.ceil(nonRatedItems.size() * 0.2));
    int tfoldSize = nonRatedItems.size() / 5;
    List<List<Integer>> negativeTestFolds = new ArrayList<List<Integer>>();
    if (tfoldSize < 1) {
        nonRatedItems.stream().map(Lists::newArrayList).collect(Collectors.toCollection(() -> negativeTestFolds));
                } else {
                    for (int i = 0; i < 5; i++) {
                        int endIndex = i < 4 ? (i + 1) * tfoldSize : nonRatedItems.size();
                        negativeTestFolds.add(nonRatedItems.subList(i * tfoldSize, endIndex));
                    }
                }

Any suggestion/help is appreciated

like image 350
Cap Avatar asked Apr 18 '26 23:04

Cap


1 Answers

Is it always 5 folds? Why not round-robin the list? something like

List<Integer>[] folds = new List<Integer>[5];
for(int i = 0; i < 5; i++)
{
   folds[i] = new LinkedList<Integer>();
}

for (int i = 0; i < nonRatedItems.size(); i++)
{
   folds[i % 5].add(nonRatedItems.get(i));
}
like image 92
Yossi Vainshtein Avatar answered Apr 20 '26 13:04

Yossi Vainshtein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!