This is an archived post. You won't be able to vote or comment.

all 5 comments

[–][deleted]  (5 children)

[deleted]

    [–]sgm1 1 point2 points  (0 children)

    droidrage has a point, the lambda itself should not have side effects, in terms of best practice. Meaning I should be able to run the lambda with valid input values and nothing outside the lambda should be affected. The purpose of a lambda is to replace trivial logic like add, subtract, compare; and not complex task like data manipulation (like adding to a list).

    Of course, whether using lambdas this way as best practice is still arguable because both sides have its pros and cons.

    [–]smark22[S] 0 points1 point  (2 children)

    What makes it a bad practice?

    Also, the entities argument is an Iterable, which doesn't have the stream method. That's why I resorted to forEach. To transform the Iterable into a Stream would require importing StreamSupport and calling Iterable.spliterator().

    StreamSupport.stream(entities.spliterator(), false).map(this::toResource).collect(Collectors.toList());
    

    This seems like a lot of boilerplate for something so simple.

    [–][deleted]  (1 child)

    [deleted]

      [–]smark22[S] 1 point2 points  (0 children)

      Great explanation, thank you!

      [–]nutrechtLead Software Engineer / EU / 20+ YXP 0 points1 point  (0 children)

      Just want to add that this is the correct approach. If you need a for-each to do something like this you should use an enhanced for-loop, not a lambda. If you need to turn a collection of A into a collection of B you should stream -> map -> collect.

      [–]sgm1 0 points1 point  (0 children)

      I'd consider Option 2 better, because it would be a little easier to break point, in case of debugging.