如何对Stream.findNth()进行编码?

编程入门 行业动态 更新时间:2024-10-24 12:26:58
本文介绍了如何对Stream.findNth()进行编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

与 Stream.findFirst()类似,有没有办法写 Stream.findNth()?

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

我正在通过重写一些遗留代码来练习Java 8。而且,我想知道如何使用Stream API编写以下函数。

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; }

我希望它能转化为:

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; }

推荐答案

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

更多推荐

如何对Stream.findNth()进行编码?

本文发布于:2023-11-26 21:16:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635222.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Stream   findNth

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!