gil.fernandes
gil.fernandes

Reputation: 14621

Copy 2D array in Java using streams

This question is related to How do I copy a 2 Dimensional array in Java?

But how would you copy an array using streams in Java 8 / 9?

This is what I came up with:

static int[][] cloneArray(int[][] array) {
    return IntStream.range(0, array.length).collect(
            () -> new int[array.length][],
            (ints, i) -> ints[i] = array[i].clone(),
            (ints, i) -> {});
}

Is there a more elegant or performant way to copy a 2D array using streams?

Upvotes: 1

Views: 1641

Answers (2)

matt
matt

Reputation: 12346

return Arrays.stream(x).map(r->Arrays.copyOf(r, r.length)).toArray(int[][]::new);

I think this is an improvement because you're not allocating a nxm array then replacing all of the m length ones with a copy.

Upvotes: 4

Holger
Holger

Reputation: 298439

You can do it straight-forwardly using

static int[][] cloneArray(int[][] x) {
    return Arrays.stream(x).map(int[]::clone).toArray(int[][]::new);
}

Note that this works for any ElementType with a public method ElementType clone(), like

static ElementType[] cloneArray(ElementType[] x) {
    return Arrays.stream(x).map(ElementType::clone).toArray(ElementType[]::new);
}

and in your case, ElementType happens to be int[].

Upvotes: 2

Related Questions