简体   繁体   English

java从Stream创建2D数组<Integer>

[英]java create 2D array from Stream<Integer>

I have Stream Stream<Integer> stream // 1,2,3,4,5,6,7,8,9 我有Stream Stream<Integer> stream // 1,2,3,4,5,6,7,8,9

I need create int[3][3] from this stream 我需要从这个stream创建int[3][3]

How can I do it? 我该怎么做?

I tried 我试过了

int[][] ints = stream
            .map(i -> new int[]{i})
            .toArray(int[][]::new);

But I get: [[1], [2], [3], [4], [5], [6], [7], [8], [9]] 但我得到: [[1], [2], [3], [4], [5], [6], [7], [8], [9]]

But I need: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 但我需要: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

EDIT: I think it is not dublicate this because I need int[3][3] array and not String[][] 编辑:我认为这不是dublicate 是因为我需要int [3] [3]数组而不是String [] []

I tried this example 我试过这个例子

int[][] array =
            IntStream.range(0, 3)
                .mapToObj(x -> IntStream.range(0, 3).boxed()
                    .toArray(Integer[]::new))
                .toArray(int[][]::new);

And I get error 我得到错误

Exception in thread "main" java.lang.ArrayStoreException: [Ljava.lang.Integer;
    at java.util.stream.Nodes$FixedNodeBuilder.accept(Nodes.java:1222)
    at java.util.stream.IntPipeline$4$1.accept(IntPipeline.java:250)
    at java.util.stream.Streams$RangeIntSpliterator.forEachRemaining(Streams.java:110)
    at java.util.Spliterator$OfInt.forEachRemaining(Spliterator.java:693)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:545)
    at java.util.stream.AbstractPipeline.evaluateToArrayNode(AbstractPipeline.java:260)
    at java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:438)
    at SparseMatrixSupportImpl.fromStream(SparseMatrixSupportImpl.java:25)
    at SparseMatrixSupportImpl.fromStream(SparseMatrixSupportImpl.java:4)
    at Main.main(Main.java:12)

EDIT: 编辑:

int[][] array = stream.collect(() -> new int[3][3],
            (a, i) -> a[(i - 1) / 3][(i - 1) % 3] = i, (a, i) -> {
            });

error 错误

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at SparseMatrixSupportImpl.lambda$fromStream$1(SparseMatrixSupportImpl.java:28)
    at java.util.stream.ReduceOps$4ReducingSink.accept(ReduceOps.java:220)
    at java.util.stream.IntPipeline$4$1.accept(IntPipeline.java:250)
    at java.util.Spliterators$IntArraySpliterator.forEachRemaining(Spliterators.java:1032)
    at java.util.Spliterator$OfInt.forEachRemaining(Spliterator.java:693)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:510)
    at SparseMatrixSupportImpl.fromStream(SparseMatrixSupportImpl.java:27)
    at SparseMatrixSupportImpl.fromStream(SparseMatrixSupportImpl.java:4)
    at Main.main(Main.java:12)



int[] values = new int[]{1, 2, 3,5,6,7,8,9,11};
Stream<Integer> integerStream = Arrays.stream(values).boxed();

You can try this code with Java 9 (this throws a compilation error in Java 8, so beware): 您可以使用Java 9尝试此代码(这会在Java 8中引发编译错误,因此请注意):

int[][] array = Stream.iterate(1, i -> i < 10, i -> i + 1).collect(() -> new int[3][3],
        (a, i) -> a[(i - 1) / 3][(i - 1) % 3] = i, (a, i) -> {});
Stream.of(array).forEach(a -> System.out.println(Arrays.toString(a)));

Here is the result: 结果如下:

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

With Java 8: 使用Java 8:

int[][] array = IntStream.range(1, 10).collect(() -> new int[3][3],
    (a, i) -> a[(i - 1) / 3][(i - 1) % 3] = i, (a, i) -> {});
Stream.of(array).forEach(a -> System.out.println(Arrays.toString(a)));

Here is another solution which supports numbers other than the pre-defined sequence (1,2,3,4,5,6,7,8,9), but is not that clean as a solution as it uses a counter array: 这是另一种支持除预定义序列(1,2,3,4,5,6,7,8,9)以外的数字的解决方案,但它不是一个干净的解决方案,因为它使用了一个计数器数组:

int[] counter = {0};
int[][] array = Stream.of(4, 2, 3, 4, 5, 8, 9, 8, 11).collect(() -> new int[3][3],
        (a, i) -> {
            a[counter[0] / 3][counter[0] % 3] = i;
            counter[0]++;
        }, (a, i) -> {});

Output: 输出:

[4, 2, 3]
[4, 5, 8]
[9, 8, 11]

If you want a bit more generic solution based on the solution above you can try this code snippet which allows to set a variable number of columns: 如果您想要基于上述解决方案的更通用的解决方案,您可以尝试此代码片段,它允许设置可变数量的列:

List<Integer> list = Arrays.asList(4, 2, 3, 4, 5, 8, 9, 8, 11, 12, 13, 17, 32, 45, 89, 91, 91, 98, 87);
int[] counter = {0};
int cols = 5;
int rows = (int) Math.ceil(list.size() / cols) + 1;
int[][] array = list.stream().collect(() -> new int[rows][cols],
        (a, i) -> a[counter[0] / cols][counter[0]++ % cols] = i, (a, i) -> {});
Stream.of(array).forEach(a -> System.out.println(Arrays.toString(a)));

The snippet above prints: 上面的代码段打印:

[4, 2, 3, 4, 5]
[8, 9, 8, 11, 12]
[13, 17, 32, 45, 89]
[91, 91, 98, 87, 0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM