简体   繁体   English

如何在Java 8中从流创建二维数组?

[英]How to create a two dimensional array from a stream in Java 8?

I have a text file like this: 我有这样的文本文件:

ids.txt ids.txt

1000
999
745
123
...

I want to read this file and load it in a two dimensional array. 我想读取此文件并将其加载到二维数组中。 I expect to have an array similar to the one below: 我希望有一个类似于下面的数组:

Object[][] data = new Object[][] { //
     { new Integer(1000) }, //
     { new Integer(999) }, //
     { new Integer(745) }, //
     { new Integer(123) }, //
     ...
};

Here is the code I wrote: 这是我写的代码:

File idsFile = ... ;
try (Stream<String> idsStream = Files.lines(idsFile.toPath(), StandardCharsets.US_ASCII)) {
    Object[][] ids = idsStream
       .filter(s -> s.trim().length() > 0)
       .toArray(size -> new Object[size][]);

    // Process ids array here...
}

When running this code, an exception is raised: 运行此代码时,会引发异常:

java.lang.ArrayStoreException: null
at java.lang.System.arraycopy(Native Method) ~[na:1.8.0_45]
at java.util.stream.SpinedBuffer.copyInto(Unknown Source) ~[na:1.8.0_45]
at java.util.stream.Nodes$SpinedNodeBuilder.copyInto(Unknown Source) ~[na:1.8.0_45]
at java.util.stream.SpinedBuffer.asArray(Unknown Source) ~[na:1.8.0_45]
at java.util.stream.Nodes$SpinedNodeBuilder.asArray(Unknown Source) ~[na:1.8.0_45]
at java.util.stream.ReferencePipeline.toArray(Unknown Source) ~[na:1.8.0_45]
... 

How can resolve this exception? 如何解决这个异常?

Given a Stream<String> you can parse each item to an int and wrap it into an Object[] using: 给定Stream<String>您可以将每个项解析为int并使用以下方法将其包装到Object[]中:

 strings
        .filter(s -> s.trim().length() > 0)
        .map(Integer::parseInt)
        .map(i -> new Object[]{i})

Now to turn that result into a Object[][] you can simply do: 现在将该结果转换为Object[][]您可以简单地执行:

Object[][] result = strings
        .filter(s -> s.trim().length() > 0)
        .map(Integer::parseInt)
        .map(i -> new Object[]{i})
        .toArray(Object[][]::new);

For the input: 输入:

final Stream<String> strings = Stream.of("1000", "999", "745", "123");

Output: 输出:

[[1000], [999], [745], [123]]

Your last line should probably be size -> new Object[size] , but you would need to provide arrays of Integers of size one and you would also need to parse the strings into Integers. 你的最后一行应该是size -> new Object[size] ,但你需要提供大小为1的Integers数组,你还需要将字符串解析为Integers。

I suggest the following: 我建议如下:

try (Stream<String> idsStream = Files.lines(idsFile.toPath(), StandardCharsets.US_ASCII)) {
    Object[][] ids = idsStream
       .map(String::trim)
       .filter(s -> !s.isEmpty())
       .map(Integer::valueOf)
       .map(i -> new Integer[] { i })
       .toArray(Object[][]::new);

    // Process ids array here...
}

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

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