Java – how to encode stream findNth()?
•
Java
And stream Similar to findfirst(), is there any way to write stream findNth()?
I'm practicing Java 8. 0 by rewriting some legacy code Also, I want to know how to write the following functions using the 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; }
I hope it will translate into:
static int skipToEntry(byte[] buf,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; }
Solution
OptionalInt result = stream.skip(n-1).findFirst();
OptionalInt result = stream.skip(n-1).findFirst();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码