Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a text file like this:

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?

like image 817
Stephan Avatar asked Jun 13 '15 10:06

Stephan


People also ask

Can I use stream in array Java?

The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source.


1 Answers

Given a Stream<String> you can parse each item to an int and wrap it into an Object[] using:

 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[][] 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]]
like image 85
Boris the Spider Avatar answered Nov 01 '22 00:11

Boris the Spider