Course contentsShow
← Java
Lesson 2080 of 2,87041. NIO.2 and the Path APIFree lesson

DirectoryStream vs Files.list: When to Use Which

Comparing lazy iteration with DirectoryStream versus Stream API convenience with Files.list for different use cases.

DirectoryStream vs Files.list: When to Use Which

You'll learn: How to choose between DirectoryStream and Files.list() based on your specific directory-listing needs.

The Core Difference

Both DirectoryStream and Files.list() let you iterate through directory contents, but they differ in when entries are loaded and how you can manipulate them:

  • DirectoryStream: A lazy iterator that fetches directory entries one-by-one as you loop through them. Think of it like reading a book page-by-page—you only see what you're currently reading.

  • Files.list(): Returns a Stream that can leverage the full Stream API (filter, map, collect, etc.). More powerful for transformations but may load more data upfront.

When to Use DirectoryStream

Choose DirectoryStream when:

  • You need simple iteration without complex transformations
  • Memory efficiency is critical (very large directories)
  • You want to stop early without loading remaining entries
  • You're applying glob patterns directly at creation time
try (DirectoryStream<Path> stream = 
     Files.newDirectoryStream(dir, "*.txt")) {
    for (Path entry : stream) {
        // Process one at a time, can break early
        if (someCondition) break; // Clean exit
    }
}

When to Use Files.list()

Choose Files.list() when:

  • You need Stream API operations (sorting, filtering chains, collectors)
  • Functional-style programming fits your code better
  • You're combining with other streams or parallel processing
  • You want concise, declarative code
try (Stream<Path> stream = Files.list(dir)) {
    long txtCount = stream
        .filter(p -> p.toString().endsWith(".txt"))
        .count();
}

Key Takeaway: Use DirectoryStream for simple, memory-efficient iteration; use Files.list() when you need the power and convenience of the Stream API for filtering, transforming, or collecting results.