JJI90
JJI90

Reputation: 59

Separating items into a 3d ArrayList

I have a 2D List of type Integer (ArrayList< List < Integer > >), There are currently 177147 lists of integers. I want to separate these into 243 different collections (Each collection having 729 lists of elements)

e.g. Array[0] -> Array[728] go into Collection[0] ...until Array[176417] -> Array[177146] goes into Collection[242]

Should I rather use ArrayList<ArrayList<List<Integer>>>? If so, how do I separate these items in this manner?

Upvotes: 0

Views: 604

Answers (2)

Florent Guillaume
Florent Guillaume

Reputation: 8343

Iterate on the elements and add by slices to the new structure:

public void run() {
    int SLICE = 729;
    List<List<Integer>> list2d = new ArrayList<List<Integer>>();
    // fill original list
    List<List<List<Integer>>> list3d = new ArrayList<List<List<Integer>>>();
    List<List<Integer>> partial = new ArrayList<List<Integer>>(SLICE);
    for (List<Integer> list : list2d) {
        partial.add(list);
        if (partial.size() == SLICE) {
            list3d.add(partial);
            partial = new ArrayList<List<Integer>>(SLICE);
        }
    }
    if (!partial.isEmpty()) {
        list3d.add(partial);
    }
}

Upvotes: 1

Jon Story
Jon Story

Reputation: 3031

for(int c = 0; c <= 242; c++)
{
    for(int i = 0; i < 729; i++)
    {
        int position = (c * 729) + i;
        Collection[c][i] = Array[position];
    }
}

You might want to check my maths on the formula for position, but the idea is sound.

Upvotes: 0

Related Questions