6

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

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.