The sorted
operation forces traversal of all the items in the stream.
Stateful operations, such as distinct and sorted, may incorporate state from previously seen elements when processing new elements.
Stateful operations may need to process the entire input before producing a result. For example, one cannot produce any results from sorting a stream until one has seen all elements of the stream.
I'm not sure, though, why the operations following the sorted
are also executed for all the elements in the stream.
If you perform the sort separately, and then use the stream for the rest of the processing, the processing will stop when the first match is found, as expected.
Arrays.sort(dataArray, Comparator.comparing(d -> d.getPriority())); // sort
Arrays.stream(dataArray)
.peek(o -> System.out.println("SORT: " + o))
.map(d -> d.getOriginalURL(shortUrl))
.peek(o -> System.out.println("MAP: " + o))
.filter(u -> u != null && !u.isEmpty())
.peek(o -> System.out.println("FILTER: " + o))
.findFirst().orElse("");