Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic tapping into a Java 8 stream using map? [duplicate]

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?

like image 606
Kedar Mhaswade Avatar asked Feb 25 '16 20:02

Kedar Mhaswade


1 Answers

You can use .peek(System.out::println) or .peek(t -> "tap: " +t.endsWith(ext))

like image 103
benjiweber Avatar answered Nov 14 '22 23:11

benjiweber