-3

I have a set of private methods that are used in a main public method (that receive a list) of a class, these methods will mainly use java 8 classic stream operations as filter, map, count e.t.c. I am wondering if creating stream single time in public api and passing to others method instead of passing list have any performance benefits or considerations as .stream() is called single time.

Juan Rada
  • 3,513
  • 1
  • 26
  • 26
  • please post the code instead of reciting the application! – ΦXocę 웃 Пepeúpa ツ Aug 07 '17 at 14:00
  • @ΦXocę웃Пepeúpaツ I do not see how 1 public method and 5 private (200 hundred lines associated with business scenario) methods in code will be more useful than statement. There is a single 4 paragraph so IMO not verbose either. – Juan Rada Aug 07 '17 at 14:26

2 Answers2

5

Calling stream() or any intermediate operation would actually do nothing, as streams are driven by the terminal operation.

So passing a Stream internally from one method to another is not bad IMO, might make the code cleaner. But dont return a Stream externally from your public methods, return a List instead ( plz read the supplied comments, might not hold for all cases)

Also think of the case that applying filter for example and then collecting to a toList and then streaming again that filtered List to only map later is obviously a bad choice... You are collecting too soon, so dont chain methods like this even internally.

Eugene
  • 117,005
  • 15
  • 201
  • 306
  • 2
    I wouldn’t rule out returning streams from `public` methods, [but that has been discussed before](https://stackoverflow.com/q/24676877/2711488)… – Holger Aug 07 '17 at 14:20
  • @Holger nice! Thank you, Ive just greped our code base and we never return `Stream`. I wonder if that should change... – Eugene Aug 07 '17 at 14:31
  • 2
    Check, how often the caller directly invokes `stream()` or `forEach()` on the returned collection… – Holger Aug 07 '17 at 14:32
  • @Holger Some usages are happy and just display the result in some form or the other. But some DB queries are re-stremed quite a lot indeed, Ill have a big code review in a day or so! Thank you – Eugene Aug 07 '17 at 14:39
0

In general it's best to ask for what is actually needed by the method. If every time you receive a list you make it a stream, ask for the stream instead (streams can come from things other than lists). This enhances portability and reusability and lets consumers of your api know upfront the requirements.

Ask for exactly what you need, nothing more, nothing less.

MaxPower
  • 881
  • 1
  • 8
  • 25