1

What is the better practice for mapping objects in Stream API?

class SomeObject{
}
class SomeComplexObject {
    private SomeObject someObject;

    public SomeObject getSomeObject() {
        return someObject;
    }
}
class SomeMoreComplexObject {
    private SomeComplexObject someComplexObject;

    public SomeComplexObject getSomeComplexObject() {
        return someComplexObject;
    }
}
List<SomeMoreComplexObject> list;

1 - subsequent map() with methods references:

list.stream()
        .map(SomeMoreComplexObject::getSomeComplexObject)
        .map(SomeComplexObject::getSomeObject);

2 - single map() with lambda:

list.stream()
        .map(smco -> smco.getSomeComplexObject().getSomeObject());

And why?

Holger
  • 285,553
  • 42
  • 434
  • 765
mmpm1223
  • 11
  • 1

1 Answers1

2

Performance ways it doesn't matter one iota.

Style wise I don't think it matters either, in that the community is not clearly committed to one way or another. Had the community standardized on one of these, there is a significant cost to breaking the mold (When in rome, be like the romans - that's usually good advice, if you care at all about writing code others can read and being able to read and integrate code others wrote; it also improves performance, as hotspot is in the end a pattern matching machine, and the patterns it has trend towards commonly used idioms).

In other words, flip a coin.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72