Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

findFirst() on SortedSet.stream()

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.

like image 226
Roben Avatar asked Jun 01 '26 22:06

Roben


1 Answers

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.

like image 117
Brian Goetz Avatar answered Jun 05 '26 01:06

Brian Goetz