0

Scenario: I have a collection of objects that I want to do some work to, transform them, and collect the results. Initially, I had two map calls:

objects.stream()
       .map(o -> {
                // do something interesting...
                // set some fields...
                return o;
            })
       .map(transformer::mapToSomethingElse)
       .collect(Collectors.toList());

My IDE recommended using .peek for the first map, since I'm just returning the same input. When I read the API notes for peek, I see the following:

This method exists mainly to support debugging

Is my usage of peek a bad idea? The operations happening within peek are necessary, so if they were optimized away, that would be bad. Due to the way this stream operation is structured, I don't have any reason to believe the peek would be elided.

Of course I could just write this with a for loop, but I like the syntax of streams so I use them wherever I can.

Fam
  • 580
  • 1
  • 7
  • 29
  • 1
    The "bad practice" you're truly running into (and not warned about) is introducing side-effects into your stream. This isn't as bad on a sequential stream, but when made parallel can become a nightmare. It's also generally against most functional programming paradigms. That said, if it works, it works, as long as you understand the implications. `#peek` would work fine if you're just returning the same reference, but `#map` may also be more self-documenting that you are mutating the stream. – Rogue Feb 09 '23 at 18:27
  • 3
    Using `map` is already bad practice, because you shouldn't modify the elements of the stream as you consume it. Side-effects should be avoided. If you want to modify the elements of a collection, use a loop. – knittl Feb 09 '23 at 18:36
  • 1
    I'm a bit unclear on the use case for streams in general. Why not use a loop in all cases? I think the answer is some problems work well (are cleanly implemented) using the stream syntax. However, some is not all. Don't force a stream implementation unless it's a clear good fit, imo. (Answering a previous question here on SO, I implemented a loop much more quickly than I could the stream equivalent, and the eventual stream version had subtle traps for the unwary. I honestly think streams are overrated.) – markspace Feb 09 '23 at 18:44

0 Answers0