[英]Java streams limit the collection elements based on condition
The below code, takes a stream, sorts it. 下面的代码采用流,对其进行排序。 If there is a maximum limit that should be applied, it would apply it.
如果存在应该应用的最大限制,则应用它。
if(maxLimit > 0) {
return list.stream().sorted(comparator).limit(maxLimit).collect(Collectors.toList());
} else {
return list.stream().sorted(comparator).collect(Collectors.toList());
}
//maxLimit, list, comparator can be understood in general terms.
Here, inside if, limit operation is present and in else, it is not present. 这里,如果存在限制操作,则在其他内部,它不存在。 Other operations on stream are same.
流上的其他操作是相同的。
Is there any way to apply limit when maxLimit is greater than zero. 当maxLimit大于零时,有没有办法应用限制。 In the code block presented above, same logic is repeated, except limit operation in one block.
在上面给出的代码块中,重复相同的逻辑,除了限制一个块中的操作。
You can split your code into parts like: 您可以将代码拆分为以下部分:
final Stream stream = list.stream()
.sorted(comparator);
if (maxLimit > 0) {
stream = stream.limit(maxLimit);
}
return stream.collect(Collectors.toList());
In this case you don't have to maintain two branches as it was in your initial example. 在这种情况下,您不必像在初始示例中那样维护两个分支。
Also when assigning stream
variable it's worth using specific generic type, eg if list
is a List<String>
then use Stream<String>
type for a stream
variable. 此外,在分配
stream
变量时,值得使用特定的泛型类型,例如,如果list
是List<String>
则使用Stream<String>
类型作为stream
变量。
list.stream().sorted(comparator).limit(maxLimit>0 ? maxLimit: list.size()).collect(Collectors.toList())
查看当前的限制实施情况,我认为它会检查限制是否小于当前大小,因此不会像我最初预期的那样低效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.