: , :
5 a section of five words 3 three words
section 2 short section 7 this section contains a lot
of words
:
[a, section, of, five, words]
[three, words, section]
[short, section]
[this, section, contains, a, lot, of, words]
, Stream API . . Stream API, StreamEx, headTail()
, . , headTail
:
public static StreamEx<List<String>> records(StreamEx<String> input) {
return input.headTail((count, tail) ->
makeRecord(tail, Integer.parseInt(count), new ArrayList<>()));
}
private static StreamEx<List<String>> makeRecord(StreamEx<String> input, int count,
List<String> buf) {
return input.headTail((head, tail) -> {
buf.add(head);
return buf.size() == count
? records(tail).prepend(buf)
: makeRecord(tail, count, buf);
});
}
:
String s = "5 a section of five words 3 three words\n"
+ "section 2 short section 7 this section contains a lot\n"
+ "of words";
Reader reader = new StringReader(s);
Stream<List<String>> stream = records(StreamEx.ofLines(reader)
.flatMap(Pattern.compile("\\s+")::splitAsStream));
stream.forEach(System.out::println);
, . reader
BufferedReader
FileReader
. : , , (, , ). , , , .
:
headTail()
, , . () , (). , . records
:
return input.headTail((count, tail) ->
makeRecord(tail, Integer.parseInt(count), new ArrayList<>()));
count
: , ArrayList
makeRecord
. makeRecord
:
return input.headTail((head, tail) -> {
head
, :
buf.add(head);
?
return buf.size() == count
, records
tail
( , ) : .
? records(tail).prepend(buf)
( ).
: makeRecord(tail, count, buf);
});