收集Java流在底层流是并行还是串行的情况下都很重要。

huangapple go评论80阅读模式
英文:

Collecting java stream matters if underlying stream is parallel or not

问题

我有如下函数:

public Stream getStream(boolean isParallel) {

...
return someSteamFromHere;
}

如果 "isParallel" 为 true,此函数将返回一个并行流,否则返回一个顺序流。现在我想要收集这个并行/顺序流。调用函数是否需要实现这个逻辑:

boolean isParallel = isParallel();
Stream stream = getStream(isParallel);
List list;
if (isParallel) {
   list = stream.parallel().collect(Collectors.toList());
} else {
   list = stream.collect(Collectors.toList());
}

还是是否可以简单地无论如何收集流,如果它是并行的,将会并行收集,如果是顺序的,将会在单个线程中收集?

英文:

I have the following function:

public Stream getStream(boolean isParallel) {

...
return someSteamFromHere;
}

This function will return a parallel stream if "isParallel" is true, otherwise a sequential stream. Now I want to collect this parallel/sequential stream. Does the caller function need to implement this logic:

boolean isParallel = isParallel();
Stream stream = getStream(isParallel);
List list;
if (isParallel) {
   list = stream.parallel().collect(Collectors.toList());
} else {
   list = stream.collect(Collectors.toList());
}

Or can i simply collect the stream regardless, and if its parallel, it will be collected in parallel and if sequential, it will be collected in a single thread?

答案1

得分: 3

并行性是流的一个属性。因此,如果你有一个并行流,在其上调用 .parallel() 是一个空操作。它绝对什么都不

英文:

parallelism is a property of the stream. So, if you have a parallel stream, calling .parallel() on this is a no-op. It does absolutely nothing whatsoever.

Note that collecting a parallel stream does imply that any concept of 'order' is right out the window.

Your code can just be List list = stream.collect(Collectors.toList());.

Note that as a general rule, if parallelism matters at all, collecting it into a list seems... bizarre. Whatever performance benefits you think you're getting from treating it parallel are pretty much obliterated when you do this.

答案2

得分: 0

为什么在函数中传入布尔值,如果你在函数返回后才使用它?要么函数接收布尔值并使用它,要么函数不获取它,测试与你编写的一样放在外部。
另外,带有布尔参数的函数被认为是代码异味,因为它们显然执行了不止一件事情。可以在这里查看。

英文:

Why do you pass in the boolean to the function if you use it after the function's return? Either the function receives the boolean and uses it or it doesn't get it and the test sits outside as you wrote.
Btw, functions with boolean parameters are considered code smell as they clearly do more than one thing. Have a look here.

huangapple
  • 本文由 发表于 2020年9月29日 06:42:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/64110561.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定