gpt4 book ai didi

java - 使用 map 惯用地进入 Java 8 流?

转载 作者:数据小太阳 更新时间:2023-10-29 07:55:17 24 4
gpt4 key购买 nike

<分区>

我非常喜欢 Ruby 的一个特性是 ability to tap into call chains .它提供了一种简单的方法来调试管道中发生的事情。我用 map 模拟了 tap:

/** 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
}

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com