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

前端 未结 2 920
星月不相逢
星月不相逢 2021-01-12 02:25

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 dimension

相关标签:
2条回答
  • 2021-01-12 02:53

    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.

    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...
    }
    
    0 讨论(0)
  • 2021-01-12 02:54

    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]]
    
    0 讨论(0)
提交回复
热议问题