Как кодировать Stream.findNth ()?
Похожий наStream.findFirst()
есть ли способ написатьStream.findNth()
?
Я практикую Java 8, переписывая некоторый унаследованный код. И мне интересно, как описанная ниже функция может быть написана с использованием Stream API.
static curPipeNumber = 0;
/** skipToEntry() updates 'curPipeNumber' to 'pipeNumber' and returns the first byte position of the word before the ('pipeNumber')-th pipe.
* It does so by reading and ignoring unnecessary bytes from the buffer.
* e.g.,
*/
static int skipToEntry(byte[] buf, int len, int nextByteToBeRead, int pipeNumber) {
if(curPipeNumber == pipeNumber)
return nextByteToBeRead;
for(; nextByteToBeRead < len; nextByteToBeRead++) {
if(buf[nextByteToBeRead] == '|') {
++curPipeNumber;
if(curPipeNumber == pipeNumber) {
return ++nextByteToBeRead;
}
}
}
return nextByteToBeRead;
}
Я надеюсь, что это будет что-то вроде:
static int skipToEntry(byte[] buf, int len, int nextByteToBeRead, int pipeNumber) {
if(curPipeNumber == pipeNumber)
return nextByteToBeRead;
OptionalInt pipeIndex = IntStream.range(i, len)
.filter(n -> buf[n] == '|')
.findNth(pipeNumber);
curPipeNumber = pipeNumber;
nextByteToBeRead = pipeIndex.getAsInt() + 1;
return nextByteToBeRead;
}