这个问题已经在这里有了答案: > Java stream “forEach” but not consuming stream 1个
我真正喜欢的Ruby功能之一是ability to tap into call chains.它提供了一种调试管道中正在发生的事情的简便方法.我用地图模拟了水龙头:
/** 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中是否有更好的(惯用的)方法?
解决方法:
您可以使用.peek(System.out :: println)或.peek(t->“ tap:” t.endsWith(ext))