JohnC
JohnC

Reputation: 171

Reading values from a file and splitting them into two lists with stream in Java

Let's say we have a file with a give input like this

List1,List2,List3,List4,List5,List6,List7.......
.....List8,List9
ListX1,ListX2,ListX3.......

After List9 entery, there is a new line character. How would I be able to tell the stream to collect elements before a new line character into a single list, and collect the rest into the second list?

List<String> fWire = new ArrayList<String>();
try (Stream<String> stream = Files.lines(Paths.get(filePath))) {
        .......
    } catch (IOException e) {
        e.printStackTrace();
    }

Upvotes: 3

Views: 150

Answers (1)

Eran
Eran

Reputation: 393791

It looks like you need a List<List<String>>. Each inner List will represent one line of input:

List<List<String>> lists = null;
try (Stream<String> stream = Files.lines(Paths.get(filePath))) {
    lists = stream.map(s -> Arrays.asList(s.split(",")))
                  .collect(Collectors.toList());
} catch (IOException e) {
    e.printStackTrace();
}

Upvotes: 1

Related Questions