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
1.1k views
in Technique[技术] by (71.8m points)

filter - Remove first element of a Stream in Java 8

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:

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.

question from:https://stackoverflow.com/questions/43121944/remove-first-element-of-a-stream-in-java-8

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

1 Answer

0 votes
by (71.8m points)

Use skip(1) to ignore the first element.

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


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

...