Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

java - How to code Stream.findNth()?

Similar to Stream.findFirst(), is there a way to write Stream.findNth()?

I'm practicing Java 8 by rewriting some legacy code. And, I'm wondering how the below function can be written using 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'm hoping it would translate to something like:

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
OptionalInt result = stream.skip(n-1).findFirst();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...