The java 8 API doc for SortedSet only states that stream() is inherited from java.util.Collection (see https://docs.oracle.com/javase/8/docs/api/java/util/SortedSet.html). This implies that the stream is sequential but may not be ordered.
So what is the safest way to ensure that sortedSet.stream().filter(...).findFirst() behaves equally to a classic for( ... ) loop returning the first matching element? Or is that already the case but just not guaranteed be the API?
(findFirst() api doc: If the stream has no encounter order, then any element may be returned.)
Stream.sorted() should do the trick, but this adds the overhead of sorting elements which are already sorted in the original set.
SortedSet has a defined encounter order, and findFirst() is guaranteed to return the first element in the encounter order, if the stream has one. So the spec already tells you what you want -- you don't need to do anything special.
BTW, sortedSet.stream().sorted() will get optimized away (since the Spliterator returned from sortedSet.stream() will have the SORTED characteristic), so doing this doesn't actually incur the cost of sorting -- but you still don't need to do it.
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