randomuser1 :
I have a java
code that provides objects from items
. It limits them based on the maxNumber:
items.stream()
.map(this::myMapper)
.filter(item -> item != null)
.limit(maxNumber)
.collect(Collectors.toList());
It works properly, but the question is - is there a way of skipping the limiting when the maxNumber == 0? I know I could do:
if (maxNumber == 0) {
items.stream()
.map(this::myMapper)
.filter(item -> item != null)
.collect(Collectors.toList());
} else {
items.stream()
.map(this::myMapper)
.filter(item -> item != null)
.limit(maxNumber)
.collect(Collectors.toList());
}
but perhaps there's a better way, does anything come to your mind? thanks!
Jean-Baptiste Yunès :
I suppose that
.limit(maxNumber == 0 ? Long.MAX_VALUE : maxNumber)
will do the trick, as it is highly non probable that you are going to tackle a stream with more than 2^63-1 elements...
At least be careful with parallel streams on this... A note in API docs says:
API Note: While
limit()
is generally a cheap operation on sequential stream pipelines, it can be quite expensive on ordered parallel pipelines, especially for large values of maxSize...