2016-02-25 85 views
3

我真的很喜歡Ruby的一個特性是ability to tap into call chains。它提供了一種簡單的方法來調試流水線中正在發生的事情。我模擬tapmap使用地圖進行Java 8流的習慣性使用習慣?

/** 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中有更好的(慣用的)方式嗎?

回答

3

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