Optional and streams
takeWhile, toList, mapMulti, useful collectors, and the bad habits inherited from Java 8.
Optional and Streams: Correct Uses and Common Misuses
Optional and the Stream API arrived together in Java 8, and that is probably their misfortune. Discovered at the same time, they were adopted as a style rather than as tools, with two consequences visible in almost every codebase. On one side, Optional everywhere: as a method parameter, as an entity field, nested inside one another, serialized in HTTP APIs. On the other, thirty-line stream chains that replace a six-line loop and that no profiler can usefully analyze anymore.
The problem is not theoretical. An Optional entity field breaks Java serialization and makes persistence frameworks fail, because Optional does not implement Serializable — that was an explicit decision by its designers. An optional.get() with no prior check turns a NullPointerException into a NoSuchElementException, which improves strictly nothing. And a poorly placed stream chain inside a hot loop costs several allocations per element where a for loop made none. This lesson goes through these two APIs, separating what they were designed for from what has been done to them, and then presents the additions made after Java 8.
Comments
Comments are powered by GitHub Discussions
Sign in with GitHub to join the discussion