简体   繁体   English

Java流根据条件限制集合元素

[英]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变量时,值得使用特定的泛型类型,例如,如果listList<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.

相关问题 使用流根据java中的条件拆分列表 - split a list based on a condition in java using streams 基于集合 java 的字段复制集合中的元素 - duplicating elements in an collection based on a field of the collection java 从Java列表中获取具有满足流条件的第n个元素的子列表 - Getting sublist from a Java list with nth elements that fulfills a condition with streams 根据不同的参数将Collection(使用Java 8流)拆分为较小的组件 - Split a Collection(using java 8 streams) into smaller components based on different parameters 基于条件设置对象值,并使用Java 8流返回布尔值 - Based on condition set object value and return boolean using java 8 streams Java 流,根据 object 中的条件进行过滤,将值设置为字符串和数组 - Java streams, filter based on condition in an object, set value to a string and a an array 使用流java8根据条件修改HashMap - Modifying HashMap based on condition using streams java8 Java/Quarkus Kafka 流式读取/写入基于条件的同一主题 - Java/Quarkus Kafka Streams Reading/Writing to Same Topic based on a condition Java 流过滤器 OR 条件 - Java streams filter OR condition 使用 Java 流仅基于属性对连续元素进行分组 - Grouping only consecutive elements based on property using Java Streams
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM