0

Say I have a list on which I need to perform operations. If I chain those operations with streaming API, is it necessary to call a terminal operation or just stopping at intermediate operations can also be fine?

list.stream().filter(some filtering).peek(some change on the filtered items);

list.stream().filter(some filtering).peek(some change on the filtered items).close();

Changing this to

 list.stream().filter(some filtering).forEach(some change on the filtered items)

does what I want.

Is there any possibility of memory leaks in the first option ? Why the peek() version doesn't work ??

Is close() a terminal operation and if it is, will this help me call setter on the filtered list items.

This question is

user2599052
  • 1,056
  • 3
  • 12
  • 27
  • Have you *tried* the first example? Does it actually do something? – luk2302 Nov 25 '19 at 09:49
  • Short answer: it depends on the underlying source. – MC Emperor Nov 25 '19 at 09:50
  • Furthermore, your example won't do anything, because you have not invoked a [terminal operation](https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps), that means that the pipeline is not executed at all. – MC Emperor Nov 25 '19 at 09:52
  • @luk2302: not ran it till now. but expect it to run the setter method on the item in the source list. Will it not ? – user2599052 Nov 25 '19 at 09:53
  • ok, so in that I need to call close() in order to make it work or is close() not a terminal operation/. – user2599052 Nov 25 '19 at 09:53
  • @luk2302 well, *both* don’t do anything. But that’s a different topic… – Holger Nov 25 '19 at 10:03
  • @Holger if you put a SysOut call into the first snippet it will not print, if you put it into the second it will do -> "the first one does not do anything" – luk2302 Nov 25 '19 at 10:05
  • 1
    @luk2302 a stream without a terminal operation will not do anything, whether you append `close()` or not. – Holger Nov 25 '19 at 10:06

0 Answers0