Shashi
Shashi

Reputation: 127

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.

Upvotes: 9

Views: 9069

Answers (2)

Szymon Stepniak
Szymon Stepniak

Reputation: 42184

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.

Upvotes: 17

Paul Harris
Paul Harris

Reputation: 5809

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

Upvotes: 19

Related Questions