0

I have an arrayList of N objects containing a few fields like so:

[
    {
        "firstName": "Todd",
        "lastName": "Jones"
    },
    {
        "firstName": "Mike",
        "lastName": "Johnson"
    },
{
        "firstName": "Tina",
        "lastName": "Jones"
    },
    {
        "firstName": "Tommy",
        "lastName": "Wiseau"
    },
    ....
]

I am trying to split a processing job into equal(ish) parts based on a passed in index of what chunk I'm currently on and how many total chunks there are.

I currently have some logic I've started that tries to do this, but I think where I am failing is that my math doesn't account for not being equally divisible. What is the best way to make sure I am always getting the correct indices in my subList?

(Example: 9 name objects, want part 1 of 2 equally split arrays)

This is my current logic that isn't working:

final int namesCount = names.size();
final int namesDividedCount = namesCount / numOfChunks;
int startIndex, endIndex;

if (chunkIndex == 1) {
  startIndex = 0;
  endIndex = namesDividedCount;
} else if (chunkIndex == numOfChunks) {
  startIndex = namesCount - namesDividedCount;
  endIndex = namesCount;
} else {
  startIndex = ((chunkIndex - 1) * namesDividedCount) + 1;
  endIndex = chunkIndex * namesDividedCount;
}
return names.subList(startIndex, endIndex);
mortimerfreeze
  • 199
  • 1
  • 1
  • 9
  • https://stackoverflow.com/questions/2895342/java-how-can-i-split-an-arraylist-in-multiple-small-arraylists – SedJ601 Aug 14 '23 at 19:41

1 Answers1

0

A quick hack just to show the logic, ignoring some of your details:

    List list = new ArrayList(List.of("a", "b", "c", "d", "e", "f", "g", "h", "i"));

    float noOfChunks = 5f;
    int chunkSize = (int) Math.ceil(list.size() / noOfChunks);

    int chunkNo = 0;
    while (list.size() > 0) {
        System.out.println(chunkNo);
        for(int i = 0; i < chunkSize; i++) {
            System.out.println("  " + list.get(0));
            list.remove(list.get(0));
            if (list.isEmpty()) {
                break;
            }
        }
        chunkNo++;
    }

The total size is divided by noOfChunks and rounded up, giving a rough chunk size, which is the processed chunk by chunk. Don't copy the inner part of the loop. It is just a way of mocking the processing part.

Sam
  • 5,424
  • 1
  • 18
  • 33