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

I have a text file:

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 like 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 this code is run, an exception is thrown:

 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 to resolve this exception?

+6
source share
2 answers

Given a Stream<String> , you can parse each element into int and wrap it in Object[] using:

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

Now, to turn this result into 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); 

To enter:

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

Output:

 [[1000], [999], [745], [123]] 
+11
source

Your last line should probably be size -> new Object[size] , but you will need to provide arrays of integers of size one, and you will also need to parse the lines in 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... } 
+5
source

Source: https://habr.com/ru/post/989056/


All Articles