以下是使用流的Java 8代码:
Set<String> getFields( Path xml ) {
final Set<String> fields = new HashSet<>();
for( ... ) {
...
fields.add( ... );
...
}
return fields;
}
void scan() {
final SortedSet<Path> files = new TreeSet<>();
final Path root = new File( "....." ).toPath();
final BiPredicate<Path, BasicFileAttributes> pred =
(p,a) -> p.toString().toLowerCase().endsWith( ".xml" );
Files.find( root, 1, pred ).forEach( files::add );
final SortedSet<String> fields = new TreeSet<>();
files
.stream()
.parallel()
.map( this::getFields )
.forEach( s -> fields.addAll( s ));
// Do something with fields...
}我希望将map( this::getFields )**,的输出(即** Stream<Set<Path>> )合并为一个 Set<Path>,并且不确定forEach的正确用法。
在Jon之后进行编辑,总结注释并编译代码
Stream<String> getFields( Path xml ) {
final Set<String> fields = new HashSet<>();
for( ... ) {
...
fields.add( ... );
...
}
return fields.stream(); // returns a stream to ease integration
}
void scan() {
final Path root = new File( "....." ).toPath();
final BiPredicate<Path, BasicFileAttributes> pred =
(p,a) -> p.toString().toLowerCase().endsWith( ".xml" );
final SortedSet<Path> files =
Files
.find( root, 1, pred )
.collect( Collectors.toCollection( TreeSet::new ));
final SortedSet<String> fields =
files
.stream()
.parallel()
.flatMap( this::getFields )
.collect( Collectors.toCollection( TreeSet::new ));
// Do something with fields...
}这两个流可以合并在一个中,但是files稍后会被重用。
发布于 2014-08-22 23:17:42
我怀疑您希望flatMap而不是map,然后使用Collectors.toCollection创建排序集:
final SortedSet<String> fields = files
.stream()
.parallel()
.flatMap(x -> getFields(x).stream())
.collect(Collectors.toCollection(() -> new TreeSet<String>());(我还没有试过,所以语法可能有点偏离,但我认为这大致是您想要的。)
通常,我建议尝试使用一种在流操作中创建集合的方法,而不是在结束时使用forEach添加所有内容--您也可以对files做同样的操作。
https://stackoverflow.com/questions/25456793
复制相似问题