Reputation: 63
How would I transform a 3 dimensional ArrayList
into a 3 dimensional array? I was reading this post about turning a 2-D ArrayList
into a 2-D array and I wondered how to extend the answer to 3-D.
Upvotes: 1
Views: 3041
Reputation: 547
This is the fantastic thing with the new functional interface:
String[][][] stringArray = mainList.stream().map(u1 -> u1.stream().map(u2 -> u2.toArray(new String[0])).toArray(String[][]::new)).toArray(String[][][]::new);
would probably work. Sadly, I have currently no access to a JRE 8 to test it, but it should chain nicely.
Simply map an additional time to propagate the arrays outward.
This works so well thanks to the way arrays works in java. An int[][]
array is actually an array of int[]
arrays. If arrays were declared with the generics notation, this would mean that an integer array with two dimensions would be of type Array<Array<Integer>>
, and so on. What the map functions does is simply utilizing this fact, and maps the ArrayList<>
objects into these "Array<>
" objects.
We simply have to do it the correct number of times.
Upvotes: 6
Reputation: 3638
This is based on the answer of the original post you refer to. I just extended it to three dimensions:
public static void main (String[] args) {
ArrayList<ArrayList<ArrayList<String>>> input;
String[][][] output;
String[][] tmp;
ArrayList<ArrayList<String>> lvl2;
ArrayList<String> lvl3;
input = new ArrayList<ArrayList<ArrayList<String>>>();
input.add(new ArrayList<ArrayList<String>>());
input.get(0).add(new ArrayList<String>());
input.get(0).get(0).add("foobar");
output = new String[input.size()][][];
for (int outer = 0; outer < input.size(); ++outer) {
lvl2 = input.get(outer);
tmp = new String[lvl2.size()][];
for (int inner = 0; inner < lvl2.size(); ++inner) {
lvl3 = lvl2.get(inner);
tmp[inner] = lvl3.toArray(new String[lvl3.size()]);
}
output[outer] = tmp;
}
}
Upvotes: 1
Reputation: 142
if you arraylist is like: A{B{C}} where:
A1 = {
B1={C1, C2, C3, ..., Cx},
B2={C1, C2, C3, ..., Cy},
...
Bm1={C1, C2, C3, ..., Cz}
A2 = {
B1={C1, C2, C3, ..., Cx},
B2={C1, C2, C3, ..., Cy},
...
Bm2={C1, C2, C3, ..., Cz}
...
An = {
B1={C1, C2, C3, ..., Cx},
B2={C1, C2, C3, ..., Cy},
...
Bmn={C1, C2, C3, ..., Cz}
to convert this arrayList to 3d array first get the proper lengths of that array
for dimension 1 proper length is size of ArrayList A => n.
for dimension 2 proper length is the max length of all B => max(m)
for dimension 3 proper length is the max length of all C => max (x,y,z)
then you can fill your array by looping through the ArrayList.
Unless if you are using Java8, there are probably more fancy ways to do it.
Upvotes: 0