流<设置<路径>>以设置<路径>

Aub*_*bin 5 java collections lambda java-8 java-stream

这是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...
}
Run Code Online (Sandbox Code Playgroud)

我想合并输出map( this::getFields ),即a Stream<Set<Path>>到aSet<Path>,我不确定正确的用法forEach.

在Jon Skeet回答总结评论并编译代码之后编辑

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...
}
Run Code Online (Sandbox Code Playgroud)

这两个流可以合并为一个,但files稍后会重复使用.

Jon*_*eet 6

我怀疑你想要flatMap而不是map,然后Collectors.toCollection用来创建有序集:

final SortedSet<String> fields = files
    .stream()
    .parallel()
    .flatMap(x -> getFields(x).stream())
    .collect(Collectors.toCollection(() -> new TreeSet<String>());
Run Code Online (Sandbox Code Playgroud)

(我没试过,所以语法可能略有偏差,但我认为这大概是你想要的.)

一般来说,我建议尝试使用一种方法,在流操作中创建一个集合,而不是forEach在最后使用添加所有内容 - 你也可以这样做files.

  • 尝试`collect(Collectors.toCollection(TreeSet :: new))`. (3认同)
  • `.MAP(这:: getFields).flatMap(设置::流).collect(...)` (2认同)