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

Categories

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

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

1 Answer

OptionalInt result = stream.skip(n-1).findFirst();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...