Listing Immediate Subdirectories Using flatMap

We saw how to list the members of a given directory. Let’s look at the effort to explore the immediate (one level deep) subdirectories in a given directory, first using a rudimentary operation and then, more conveniently, using the flatMap method.

Let’s use the traditional for loop first to iterate over the files in a given directory. If a subdirectory contains any files, we’ll add them to our list; otherwise, we’ll add the subdirectory itself to the list. Finally, we’ll print the total number of files found. Here’s the code—for the hard way.

compare/fpij/ListSubDirs.java
 
public​ ​static​ ​void​ listTheHardWay() {
 
List​<​File​> files = ​new​ ​ArrayList​<>();
 
 
File​​[]​ filesInCurrentDir ...

Get Functional Programming in Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.