One feature of Ruby I really like is the ability to tap into call chains. It provides an easy way to debug what is going on in a pipeline. I simulated tap
with a map
:
/** Searches recursively and returns the path to the dir that has a file with given extension,
* null otherwise.
* Returns the given dir if it has a file with given extension.
* @param dir Path to the start folder
* @param ext String denotes the traditional extension of a file, e.g. "*.gz"
* @return {@linkplain Path} of the folder containing such a file, null otherwise
*/
static Path getFolderWithFilesHavingExtension(Path dir, String ext) {
Objects.requireNonNull(dir); // ignore the return value
Objects.requireNonNull(ext); // ignore the return value
try {
Optional<Path> op = Files.walk(dir, 10).map((t) -> {
System.out.println("tap: " + t.endsWith(ext));
System.out.println("tap: " + t.toString().endsWith(ext));
return t;
}).filter(p -> p.toString().endsWith(ext)).limit(1).findFirst();
if (op.isPresent())
return op.get().getParent();
} catch (IOException e) {
return null; // squelching the exception is okay? //TODO
}
return null; // no such files found
}
This actually helped me fix a bug in that I was doing Path::endsWith
instead of String::endsWith
to see if the file name ends with a particular extension.
Is there a better (idiomatic) way of doing it in Java 8?
You can use .peek(System.out::println)
or .peek(t -> "tap: " +t.endsWith(ext))
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