gpt4 book ai didi

java - Stream> 到 Set

转载 作者:搜寻专家 更新时间:2023-10-31 19:54:56 24 4
gpt4 key购买 nike

这是使用流的 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 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...
}

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

最佳答案

我怀疑您想要 flatMap 而不是 map,然后使用 Collectors.toCollection 创建排序集:

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

(我还没有尝试过,所以语法可能稍微不对,但我认为这大致就是您想要的。)

一般来说,我会建议尝试使用一种在流操作中创建集合的方法,而不是在最后使用 forEach 来添加所有内容 - 您可以对 files 执行相同的操作

关于java - Stream<Set<Path>> 到 Set<Path>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25456793/

24 4 0