当前位置: 首页 > 面试题库 >

如何编写Stream.findNth()?

唐涛
2023-03-14
问题内容

类似于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;
}

问题答案:
OptionalInt result = stream.skip(n-1).findFirst();


 类似资料:
  • 如果你写了一个很棒的starter,恳请告知我们,报个issue即可,码云或者github均可 https://gitee.com/nutz/nutzboot https://github.com/nutzam/nutzboot 基本结构 与NB项目一样, starter也是maven项目 - src - main - java - net

  • 问题内容: 我正在将iPhone应用程序作为一个业余项目编写,它将需要一个Web服务来为其提供数据。它与我在工作中没有太大区别,但在工作中我只编写视图和控制器。其他人负责编写模型,通常由客户端提供Web服务。 以前,当每个人都使用MySQL和PHP时,我已经做过一些Web编程,所以我的技能有些过时了,但是我有信心,我可以使用我已经知道的技术来完成它。但是,我不想浪费时间使用过时的工具。我发现最先进

  • ##用于写一个 h2 头。每个文档必须以 h2 开头。 这是为了支持 appium.io 文档生成。不要使用---下划线方法创建标题。 不要对标题使用 h1 # 或 ===,因为目录表不支持这样(文件夹名称将用作 h1)。 副标题 ### 用于编写副标题 常规标题 #### 用于不出现在目录里的标题。 不要使用 h5 ##### 或是 h6 ######。 换行符 不要使用 -- 或者 ---这样

  • 问题内容: 我想知道如何编写探查器?推荐哪些书籍和/或文章?谁能帮我吗? 有人已经做了这样的事情? 问题答案: 我将首先看一下那些开源项目: Eclipse TPTP(http://www.eclipse.org/tptp/) VisualVM(https://visualvm.dev.java.net/) 那我看看JVMTI(不是JVMPI) http://java.sun.com/develo

  • 问题内容: 我简要阅读了有关Maxine的信息,这是一个用Java编写的开源JVM实现。这对我来说听起来很圆。如果java要求运行虚拟机,那么如何用Java编写虚拟机本身(VM代码是否需要运行VM的虚拟机,依此类推?)。 编辑 :好的,所以我看到我忽略了Java不必在VM中运行的事实。那如何解释如何用LISP编写LISP编译器呢?还是这完全是一个新问题? 问题答案: 最初,您认为Java需要虚拟机

  • 关于代理,Java消息服务是如何工作的?我看到了创建producer的教程和示例