Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java8 stream of arrays to 2 dimensional array

I'm new to Java8 and I can't use streams to map one array into another 2 dimensional array.

I have one 2-dimensional array which is a pattern:

boolean[][] pattern = {
            {true, true, false},
            {true, false, true},
            {false, true, true}
    };

And second array which contains keys.

0 means: take 0-element from pattern

1 means: take 1-element from pattern and so on

int[] keys = {2, 1, 0};

From these 2 arrays I'd like to produce another 2-dimensional array. In this case the result will look like this:

boolean[][] result = {
                {false, true, true},
                {true, false, true},
                {true, true, false}
        };

This is the code in Java7:

public boolean[][] producePlan(int[] keys, boolean[][] pattern) {
        boolean[][] result = new boolean[keys.length][];
        for (int i = 0; i < keys.length; i++) {
            result[i] = pattern[keys[i]];
        }
        return result;
    }

In Java8 I'm only able to print every row

Arrays.stream(keys).mapToObj(x -> pattern[x]).forEach(x -> System.out.println(Arrays.toString(x)));

but can't transform it into 2-dimensional array.

Please help

like image 584
danski88 Avatar asked Aug 01 '18 01:08

danski88


1 Answers

You can do it like so,

boolean[][] result = Arrays.stream(keys).mapToObj(i -> pattern[i]).toArray(boolean[][]::new);

Since you have Stream<boolean[]> after the map stage, you only need to provide an array generator function.

like image 90
Ravindra Ranwala Avatar answered Oct 16 '22 14:10

Ravindra Ranwala