java.nio.file.Files.walk() sorting guarantee?

37 Views Asked by At

The java nio Files API gives several options to list the contents of a directory:

I am looking for a way to be able to recursively enumerate contents of a directory sorted by name.

The Javadoc of the methods do not mention anything about it, but is there any implicit guarantee about the order of the returned Path objects for these methods?

1

There are 1 best solutions below

0
Sweeper On

No order is guaranteed. The documentation for both list and 3-arg walk says:

The returned stream encapsulates one or more DirectoryStreams.

The documentation for DirectoryStream says:

The elements returned by the iterator are in no specific order.

So you should just call sorted on the stream with a comparator of your choice.