0

I have the following line stream that I read from a file

1     2   4.5

1 6 3     5.5   5.3   6

1 7.2     5     7

How can I collect these lines in a single list of list considering only the Integers? (Notice that within each line the numbers are separated by one or more white spaces)

This is what I tried, but this give me one single list of all integer elements.

        list = reader.lines()
            .map(m -> m.split("\\n"))
            .flatMap(Arrays::stream)
            .map(m -> m.split("\\s+"))
            .flatMap(Arrays::stream)
            .filter(f -> !f.contains("."))
            .map(Integer::parseInt)
            .collect(Collectors.toList());
0

2 Answers 2

6
reader.lines()
   .map(line -> Arrays.stream(line.split("\\s+"))
                      .filter(f -> !f.contains("."))
                      .map(Integer::parseInt)
                      .collect(Collectors.toList())
   .collect(Collectors.toList())
Sign up to request clarification or add additional context in comments.

1 Comment

You're right. lines() is self explanatory. It already return the lines one by one. And I didn't know I could create a new stream inside the map function. Got the strategy! Thanks for the support!
3

This should do the trick.

list = reader.lines()
    .map(line -> Arrays.stream(line.split("\\s+"))
        .filter(number -> !number.contains("."))
        .map(Integer::parseInt)
        .collect(Collectors.toList()))
    .collect(Collectors.toList());

You may also want to filter for empty lines:

 list = reader.lines()
    .map(line -> Arrays.stream(line.split("\\s+"))
        .filter(number -> !number.contains("."))
        .map(Integer::parseInt)
        .collect(Collectors.toList()))
    .map(l -> !l.isEmpty())
    .collect(Collectors.toList());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.