3

I want to make a program that does calculations on different multidimensional arrays, or really just the simple task of printing it. I am hoping to have the function parameters that sort of look like

printArray(Int Array of any dimensions, int dimensions, int... sizes)

One goal for calculations is the mode, so I am thinking of flattening out all the arrays to do any calculations or modifications.

I've looked into how arrays and stream can be used to flatten out an array.

2d:

Arrays.stream(arr).flatMap(Arrays::stream).flatMapToInt(Arrays::stream).toArray();

3d:

Arrays.stream(arr).flatMap(Arrays::stream).flatMap(Arrays::stream).flatMapToInt(Arrays::stream).toArray();

but it also is not generic since every dimension it requires another ".flatMap". And I still don't know how to make that kind of parameters that accept any dimensions.

Minyi Lu
  • 31
  • 1
  • https://stackoverflow.com/questions/3104504/is-it-possible-to-dynamically-build-a-multi-dimensional-array-in-java, anyway what is wrong with (dynamic) ArrayList ? – PeterMmm Aug 10 '19 at 18:27
  • I think the stream is not where you should solve this. Rather, think about how you could represent this as a class and pass one of those in. – Bohemian Apr 30 '23 at 14:41

1 Answers1

0

I think this would do the trick:

var arrStr = Arrays.stream(arr);
    
var counter = 0;
while(dimensions > counter)
{
    arrStr = arrStr.flatMap(Arrays.stream);
}
return arrStr.flatMapToInt(Arrays::stream).toArray();

Admittedly this is rather of an imperative style and may be improved on.