使用地图习惯性地利用 Java 8 流?

Ked*_*ade 4 ruby java java-8 java-stream

我非常喜欢 Ruby 的一项功能是能够利用调用链。它提供了一种调试管道中正在发生的事情的简单方法。我tap用一个模拟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
}
Run Code Online (Sandbox Code Playgroud)

这实际上帮助我修复了我正在做的一个错误,Path::endsWith而不是String::endsWith查看文件名是否以特定扩展名结尾。

在 Java 8 中有更好的(惯用的)方法吗?

小智 5

您可以使用.peek(System.out::println).peek(t -> "tap: " +t.endsWith(ext))