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


i have text file this:

ids.txt

1000 999 745 123 ... 

i want read file , load in 2 dimensional array. expect have array similar 1 below:

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

here code 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 code, exception raised:

java.lang.arraystoreexception: null @ java.lang.system.arraycopy(native method) ~[na:1.8.0_45] @ java.util.stream.spinedbuffer.copyinto(unknown source) ~[na:1.8.0_45] @ java.util.stream.nodes$spinednodebuilder.copyinto(unknown source) ~[na:1.8.0_45] @ java.util.stream.spinedbuffer.asarray(unknown source) ~[na:1.8.0_45] @ java.util.stream.nodes$spinednodebuilder.asarray(unknown source) ~[na:1.8.0_45] @ java.util.stream.referencepipeline.toarray(unknown source) ~[na:1.8.0_45] ...  

how can resolve exception?

given stream<string> can parse each item int , wrap object[] using:

 strings         .filter(s -> s.trim().length() > 0)         .map(integer::parseint)         .map(i -> new object[]{i}) 

now turn result object[][] can do:

object[][] result = strings         .filter(s -> s.trim().length() > 0)         .map(integer::parseint)         .map(i -> new object[]{i})         .toarray(object[][]::new); 

for input:

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

output:

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

Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -