Meenamma
Meenamma

Reputation: 47

Is stream() method lazy? If lazy then can this method itself considered intermediate as it is for returning a stream?

List<Item> applePhones = list.stream()
            .filter((item) -> item.getCompany().equalsIgnoreCase("Apple"))
            .filter((item) -> item.getDevice().equalsIgnoreCase("Phone"))
            .collect(Collectors.toList());

here these filter operations are intermediate and collect is terminal then what the stream call is?

Upvotes: 0

Views: 84

Answers (1)

ernest_k
ernest_k

Reputation: 45319

The short answer is stream() as you used it, is not a Stream method (It's Collection.stream). And that means that the intermediate vs terminal or lazy vs eager distinctions of stream methods/operations are irrelevant.

List.stream in this case represents the source of the stream. Having a stream object, you then invoke intermediate and/or terminal operations on it (filter and collect in your example). That's a simple way to put it to avoid getting philosophical.

The way I understand it (probably oversimplified):

  • streamObject.operation() -> Stream: intermediate/lazy stream operation (stream.filter(), stream.map(), etc.)
  • streamObject.operation() -> something else or void: terminal stream operation (stream.collect(), stream.count(), etc.)
  • somethingElse.stream() -> Stream: source (I don't think source is "the name" for this stream factory/creator concept, although that's what the java.util.stream package docs refer to this as, as far as I can see) - (list.stream(), Arrays.stream(), Stream.of(), optional.stream(), reader.lines(), etc.)

Upvotes: 1

Related Questions