2016-07-12 24 views
0

基於之前的過濾結果,可以如何簡化流搜索?基於之前的過濾結果,可以如何簡化流搜索?

HashMap<Boolean, List<Path>> result = (HashMap<Boolean, List<Path>>) Files.walk(Paths.get(folder)).map(Path 
      ::toAbsolutePath).collect(Collectors.groupingBy(Files::isSymbolicLink)); 
    result.get(true).stream().filter(path -> { 
     try { 
      return !result.get(false).contains(Files.readSymbolicLink(path)); 
     } catch (IOException e) { 
      throw Throwables.propagate(e); 
     } 
    }).forEach(symbolicLink -> { 
     try { 
      result.get(false).addAll(Files.walk(symbolicLink, FileVisitOption.FOLLOW_LINKS).collect(Collectors 
        .toList())); 
     } catch (IOException e) { 
      throw Throwables.propagate(e); 
     } 
    }); 

    return result.get(false).stream().filter(Files::isRegularFile).distinct().collect(Collectors.toList()); 

回答

1

你可以通過提取部分代碼的進入方法,並通過使用HashMap避免收拾一下吧。

而不是HashMap您可以將文件存儲在Set<Path>。這強制了唯一性,所以您並不需要麻煩檢查符號鏈接是否導致您已有的文件,並且可以刪除一些過濾:

public Set<Path> getAllFiles(final String folder) throws IOException { 
    return Files.walk(Paths.get(folder)) 
      .map(Path::toAbsolutePath) 
      .flatMap(this::getAllFiles) 
      .collect(Collectors.toSet()); 
} 

private Stream<Path> getAllFiles(final Path path) { 
    if(!Files.isSymbolicLink(path)) return Stream.of(path); 
    try { 
     return Files.walk(path, FileVisitOption.FOLLOW_LINKS) 
       .filter(Files::isRegularFile); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return Stream.empty(); 
}