1

Given a list of int[] [{7, 0}, {7, 1}, {6, 1}, {5, 0}, {5, 2}, {4, 4}] I need to convert it into 2D Array {{7, 0}, {7, 1}, {6, 1}, {5, 0}, {5, 2}, {4, 4}} using Java 8.

Before Java 8 we could use the following logic: temp is List<int[]> which contains above list of elements. First res[][] is created of the same size as a List of elements in temp.

int[][] res = new int[temp.size()][2];
for (int i = 0; i < temp.size(); i++) {
   res[i][0] = temp.get(i)[0];
   res[i][1] = temp.get(i)[1];
}
1
  • This worked with java 8+. I don't think your problem has anything to do with the java version you are using or don't understand what is the problem at all. Commented Jul 6, 2020 at 2:50

1 Answer 1

2

Try this.

List<int[]> list = List.of(
    new int[] {7, 0}, new int[] {7, 1},
    new int[] {6, 1}, new int[] {5, 0},
    new int[] {5, 2}, new int[] {4, 4});
int[][] res = list.stream().toArray(int[][]::new);
System.out.println(Arrays.deepToString(res));

result

[[7, 0], [7, 1], [6, 1], [5, 0], [5, 2], [4, 4]]

See this code run live at IdeOne.com.

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

3 Comments

Up-voted, but list.toArray(int[][]::new) (without the stream() call) works quiet as well too, but is Java 11+. For all Java versions, not just Java 8+, list.toArray(new int[0][]) works great.
List.of is also java 9+, I don't know if using streams is any better in this case and if it solves the OP problem, if there was any.
Mind that this makes a shallow copy. The example code in the question does a deep copy.

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.