Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 453
Manolo Pirolo Avatar asked Mar 30 '17 15:03

Manolo Pirolo


People also ask

How do you remove the first element from a stream?

Stream skip(n) method is used to skip the first 'n' elements from the given Stream.

How do I remove the first element from a list in Java 8?

We can use the remove() method of ArrayList container in Java to remove the first element. ArrayList provides two overloaded remove() method: remove(int index) : Accept index of the object to be removed. We can pass the first element's index to the remove() method to delete the first element.

How do I remove the first element from an array in Java?

To remove first element of an Array in Java, create a new array with the size one less than the original array size, and copy the elements of original array, from index=1, to new array.

What is Skip method in Java 8?

The skip(n) method is an intermediate operation that discards the first n elements of a stream. The n parameter can't be negative, and if it's higher than the size of the stream, skip() returns an empty stream.


1 Answers

Stream#skip

Use skip(1) to ignore the first element.

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

like image 70
Kayaman Avatar answered Oct 06 '22 00:10

Kayaman