在 Java 8 中删除流的第一个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43121944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:05:52  来源:igfitidea点击:

Remove first element of a Stream in Java 8

javafilterfunctional-programmingjava-streamjava.nio.file

提问by Manolo Pirolo

I have generated a Stream in Java 8 with Files.walk() method from java.nio library. The problem is that the method includes by default the root path but I do not want this element. I have solved in this case with this code using filter() method:

我已经使用 java.nio 库中的 Files.walk() 方法在 Java 8 中生成了一个流。问题是该方法默认包含根路径,但我不想要这个元素。在这种情况下,我使用 filter() 方法解决了此代码:

public void listFiles(String directoryPath) {
    try {
        Path root = Paths.get(directoryPath);
        Files.walk(root,1)
            .filter(x -> !x.equals(root))
            .forEach(System.out::println);
    } catch (IOException ex) {
        System.err.println("Error reading file: " + directoryPath);
    }
}

My question is if there is a way more elegant to remove the first element of a Stream than this. For example working with a index in the Stream or with a tail() method as others functional languages.

我的问题是,是否有比这更优雅的方法来删除 Stream 的第一个元素。例如使用 Stream 中的索引或使用 tail() 方法作为其他功能语言。

回答by Kayaman

Use skip(1)to ignore the first element.

使用skip(1)忽略第一个元素。

Don't use it with parallel streams without reading the disclaimer in the javadoc.

不要在没有阅读 javadoc 中的免责声明的情况下将它与并行流一起使用。