How can I get a parallel stream of Files.walk?
You can transform any Stream
into a parallel Stream
by invoking Stream::parallel
.
Stream<Path> stream = Files.walk(startPath).parallel().forEach(...);
I had the same issue. The Files.walk stream does not seem to work parallel. Ever afer transforming the stream into a parallel stream by invoking parallel()
the processing was performed in one thread only.
The only solution was to transform collected the Paths
in a list and create a parallel stream on this list as mentioned by Tagir Valeev.
Not working solution:
Files.walk(Paths.get(System.getProperty("user.dir")))
.parallel()
.filter(Files::isRegularFile)
...
Working solution:
Files.walk(Paths.get(System.getProperty("user.dir")))
.collect(Collectors.toList())
.parallelStream()
.filter(Files::isRegularFile)
...