Operator-Elision bei Streams

Bin da gerade drüber gestolpert:

Listing 1. Stream pipeline in which operations can be automatically elided
TreeSet<String> ts = ...
String[] sortedAWords = ts.stream()
                          .filter(s ‑> s.startsWith("a"))
                          .sorted()
                          .toArray();

The stream flags for the source stage include SORTED , because the source is a TreeSet . The filter() method preserves the SORTED flag, so the stream flags for the filtering stage also include the SORTED flag. Normally, the result of the sorted() method would be to construct a new pipeline stage, add it to the end of the pipeline, and return the new stage. However, because it’s known that the elements are already sorted in natural order, the sorted() method is a no-op — it just returns the previous stage (the filtering stage), since sorting would be redundant.

(von IBM Developer, H.v.m)

Irgendwie hatte ich nicht auf dem Schirm, dass Streams so „intelligent“ sind (oder sein können, wenn die Stream characteristics sauber verwaltet werden).

Gut zu wissen, IMHO…

2 „Gefällt mir“