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());
asked Oct 3, 2016 at 18:18
2 Answers 2
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
thiagogcm
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!
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
lang-java