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. In the code block presented above, same logic is repeated, except limit operation in one block.
IntStream limit() method in Java The limit() method of the IntStream class is used to return a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length. Here, maxSize is the parameter. Here, the maxSize parameter is the count of elements the stream is limited to.
No storage. Streams don't have storage for values; they carry values from a source (which could be a data structure, a generating function, an I/O channel, etc) through a pipeline of computational steps.
The limit method of the Stream class introduced in Java 8 allows the developer to limit the number of elements that will be extracted from a stream. The limit method is useful in those applications where the user wishes to process only the initial elements that occur in the stream.
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, e.g. if list
is a List<String>
then use Stream<String>
type for a stream
variable.
list.stream().sorted(comparator).limit(maxLimit>0 ? maxLimit: list.size()).collect(Collectors.toList())
Looking at the current implementation of limit i believe it checks to see if the limit is less than the current size so would not be as inefficient as i initially expected
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With