简体   繁体   中英

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.

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.

Right, SortedSet inherits stream() javadoc from Collection , but what you should really look is spliterator() javadoc. This is an excerpt:

The {@code Spliterator} reports {@link Spliterator#DISTINCT} , {@link Spliterator#SORTED} and {@link Spliterator#ORDERED} .

Note the Spliterator.SORTED characteristic. This means that every implementation of SortedSet must return a sorted stream. So, sortedSet.stream().findFirst() always returns the lowest element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM