2015-12-19 121 views
1

我有这样动态滤波器链的Java 8

private void processFiles() { 
     try { 
      Files.walk(Paths.get(Configurations.SOURCE_PATH)) 
        .filter(new NoDestinationPathFilter()) //<--This one 
        .filter(new NoMetaFilesOrDirectories()) //<--and this too 
        .forEach(
          path -> { 
           new FileProcessorFactory().getFileProcessor(
             path).process(path); 
          }); 
     } catch (IOException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 
    } 

一个码作为我现在有各种其它方法,这是与上述相同之一,在过滤器中唯一的区别。一些方法有额外的过滤器,一些有不同的或没有。

是否有可能创建一个条件所需的过滤器集合并动态传递。并且集合中的所有过滤器都应用于流中。我不想对正在应用的过滤器列表进行硬编码。 我想使其基于配置。 我该如何做到这一点?

+0

参见http://stackoverflow.com/questions/22845574/how-to-dynamically-do-filtering-in-java-8 –

回答

5

你可以用Files.find()

private void processFiles(final Path baseDir, final Consumer<? super Path> consumer, 
    final Collection<BiPredicate<Path, BasicFileAttributes>> filters) 
    throws IOException 
{ 
    final BiPredicate<Path, BasicFileAttributes> filter = filters.stream() 
     .reduce((t, u) -> true, BiPredicate::and); 

    try (
     final Stream<Path> stream = Files.find(baseDir, Integer.MAX_VALUE, filter); 
    ) { 
     stream.forEach(consumer); 
    } 
} 

是的,这将意味着转换您的过滤器...

参见的BiPredicateBasicFileAttributes javadoc的;特别是BiPredicate有一个.and()方法,你会发现你的情况有用。

+0

我想这不会帮助我。代码结构将从.filter更改为.and但仍然会保留在代码中。我想使它的配置基于 –

+1

你没有告诉任何有关基于配置的内容......此外,请注意,与你不同的是,我正确关闭了流。 – fge

+0

你知道了,你现在编辑根据我的需要 –

1

这个怎么样?

private void processFiles(List<Predicate<Path>> filterList) { 
    Predicate<Path> compositeFilter=filterList.stream().reduce(w -> true, Predicate::and); 
    try { 
     Files.walk(Paths.get(Configurations.SOURCE_PATH)) 
      .filter(compositeFilter) 
      .forEach(path -> { 
         new FileProcessorFactory().getFileProcessor(
           path).process(path); 
        }); 

    } catch (IOException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 
} 
+1

请注意,你不需要在这里写你的lambda表达式作为语句。而不是'path - > {new FileProcessorFactory()。getFileProcessor(path).process(path); }'您可以简单地写'path - > new FileProcessorFactory()。getFileProcessor(path).process(path)'... – Holger