Skip to content
Advertisement

Collect a stream after an objects attribute exceeds a certain threshold

Assume I have a list of custom objects MaDate with a field temp of type int. I want to use streams to get all items after the first hits a certain threshold MaDate.temp >= 10 .

JavaScript

And

JavaScript

Ideally the result list should contain the last 3 elements having temp values [10,3,9].

I can not use filter

JavaScript

because this would eliminate every object with value under 10. And I can not also use skip

JavaScript

because I do not know the index beforehand. I can not use

JavaScript

because I need all objects after the treshold was reached once regardles which values the objects have after that.

Can I combine those above somehow to get what I want or write my own method to put in skip or filter

JavaScript

or

JavaScript

?

Advertisement

Answer

If I understand your question correctly then you can use Stream#dropWhile(Predicate):

Returns, if this stream is ordered, a stream consisting of the remaining elements of this stream after dropping the longest prefix of elements that match the given predicate. Otherwise returns, if this stream is unordered, a stream consisting of the remaining elements of this stream after dropping a subset of elements that match the given predicate.

Example:

JavaScript

Note that dropWhile was added in Java 9. This Q&A shows a workaround if you’re using Java 8: Limit a stream by a predicate.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement