3

I'm wondering if there is any significant difference between two cases of flatmapping.

Case 1:

someCollection
    .stream()
    .map(CollectionElement::getAnotherCollection)
    .flatMap(Collection::stream);

Case 2:

someCollection
    .stream()
    .flatMap(element -> element.getAnotherCollection().stream());

Which one should be prefered? Is any of these better in terms of performance?

Druckles
  • 3,161
  • 2
  • 41
  • 65
Fossan
  • 76
  • 1
  • 9

1 Answers1

5

Which one should be preferred?

The difference is so cosmetic that it's up to you and your team - pick the one that you feel more comfortable with. I'd go for the second option, it's more concise.

Is any of these better in terms of performance?

From the time complexity point of view, no. The first example involves a creation of a few unnecessary objects, so the second one is a more reasonable choice. However, keep in mind that we're talking about micro-optimizations here.

Grzegorz Piwowarek
  • 13,172
  • 8
  • 62
  • 93
  • I'd add that the cosmetic differences may make a difference in terms of editability. It may be easier, for instance, to add a `filter` or another `map` between the calls to `map` and `flatMap` in the first example. Which might also be a disadvantage, but that would be a topic for codereview.stackexchange.com. And the 'conciseness' is also a matter of subjectivity ;-) – Druckles Jul 31 '18 at 12:30
  • what are the objects that are created in the first example? I don't know Java's stream implementation well enough, but would it not optimise them out? – Druckles Jul 31 '18 at 12:32
  • @Druckles all true but keep in mind that the above task is strictly about flattening the stream structure - if you need a filter/map in between, you could as well add it after the single flatMap call. Regarding the additional costs in the second example, there's quite a lot happening even inside a single map() call to add another operation to the ReferencePipeline. So, not only you create another Stream object, another functional interface representation + code triggered by map() call. It will be optimized by JVM but at the end of the day, someone needs to collect the garbage – Grzegorz Piwowarek Jul 31 '18 at 12:39