0

There is a simple query that filters a list and gets a field value of the item found.

myList.getParents().stream()
                .filter(x -> x.getSomeField() == 1)
                .map(x -> x.getOtherField())
                .findFirst();

Are operations executed one after one as in code: from initial list we filter all where someField is 1, after it we create new list with a value of another field and after it we take the first one in this new list?

Let's imagine that there are 1 000 000 items in this list and after filtering they are 1000. Will it map those 1000 items to get only first one of them?

If I change the order will it optimize the performance or is it smart enough itself?

myList.getParents().stream()
   .filter(x -> x.getSomeField() == 1)
   .findFirst()
   .map(x -> x.getOtherField());
Vitalii
  • 10,091
  • 18
  • 83
  • 151
  • 2
    from the docs: *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.* – Jack Flamp Jun 26 '18 at 07:11
  • 1
    I think second one is good because map function do in Optional not in stream. – janith1024 Jun 26 '18 at 07:18
  • 1
    see https://stackoverflow.com/questions/44862517/are-java-streams-stages-sequential/44862584#44862584 – Ousmane D. Jun 26 '18 at 10:25

1 Answers1

2

No, in Java8 stream processing pipeline one data item is processed in one single pass. That way we can perform short circuit evaluations and gives us more room to optimize.

For instance in your case we take the first item, applies the filter, assume it satisfies the filter criteria. Then we go ahead and do the mapping and push that element. We don't need to access any other element in the stream source, since we process it in one pass. This short circuit evaluation allows us to do more optimizations.

However the second representation of processing pipeline is wrong. You can't have map at the end. The terminal operation findFirst should be at the end of the pipeline though.

Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63