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());
apophis
3743 silver badges11 bronze badges
asked Oct 3, 2016 at 18:18
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())
Vladimir Vagaytsev
2,8919 gold badges36 silver badges38 bronze badges
answered Oct 3, 2016 at 18:23

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());
answered Oct 3, 2016 at 18:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.