Java threads restrict collection items based on condition

In the code below, it takes a stream, sorts it. If there is a maximum limit to be applied, he will 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, is there a limit operation, and otherwise it does not exist. Other operations in the stream are the same.

Is there a way to apply the limit when maxLimit is greater than zero. In the above code block, the same logic is repeated, with the exception of the restriction operation in one block.

+4
source share
2 answers
list.stream().sorted(comparator).limit(maxLimit>0 ? maxLimit: list.size()).collect(Collectors.toList())

Looking at the current implementation of the limit, I believe that it checks if the current limit does not exceed the current size, so it will not be as inefficient as I originally expected

+5
source

, :

final Stream stream = list.stream()
        .sorted(comparator);

if (maxLimit > 0) {
    stream = stream.limit(maxLimit);
}

return stream.collect(Collectors.toList());

, .

stream , . list List<String>, Stream<String> stream.

+11

Source: https://habr.com/ru/post/1687318/


All Articles