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.
Stream skip(n) method is used to skip the first 'n' elements from the given Stream.
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.
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.
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.
Stream#skip
Use skip(1) to ignore the first element.
Don't use it with parallel streams without reading the disclaimer in the javadoc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With