Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. In the code block presented above, same logic is repeated, except limit operation in one block.

like image 841
Shashi Avatar asked Oct 11 '17 15:10

Shashi


People also ask

How do you limit a stream in Java?

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.

Do streams have limited storage in Java?

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.

What is the purpose of limit method of stream in Java 8?

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.


2 Answers

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.

like image 196
Szymon Stepniak Avatar answered Nov 05 '22 23:11

Szymon Stepniak


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

like image 25
Paul Harris Avatar answered Nov 05 '22 23:11

Paul Harris