Jose Reyes
Jose Reyes

Reputation: 101

Is sort applied before map in Java Streams?

I want to process a List using Java streams, but not sure if I can guarantee the sort is processed before the map method in the following expression:

list.stream()
            .sorted((a, b) -> b.getStartTime().compareTo(a.getStartTime()))
            .mapToDouble(e -> {
                        double points = (e.getDuration() / 60);
                        ...                             
                        return points * e.getType().getMultiplier();
                    }
            ).sum();

Since I need to perform some calculations based in that specific order.

Upvotes: 1

Views: 1092

Answers (2)

Eugene
Eugene

Reputation: 120848

Not only sorted will be applied before map, but it will obviously traverse the underlying source. sorted will get all the elements, put them into an array or ArrayList (depending if the size is known), sort that and them give one element at a time to the map operation.

Upvotes: 0

fps
fps

Reputation: 34460

Yes, you can guarantee that, because the operations in the stream pipeline are applied in the order they are declared (once a terminal operation has been executed).

From Stream docs:

To perform a computation, stream operations are composed into a stream pipeline. A stream pipeline consists of a source (which might be an array, a collection, a generator function, an I/O channel, etc), zero or more intermediate operations (which transform a stream into another stream, such as filter(Predicate)), and a terminal operation (which produces a result or side-effect, such as count() or forEach(Consumer)). Streams are lazy; computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only as needed.

The key word in the above paragraph is pipeline, whose definition in Wikipedia starts as follows:

In software engineering, a pipeline consists of a chain of processing elements (processes, threads, coroutines, functions, etc.), arranged so that the output of each element is the input of the next...

Upvotes: 1

Related Questions