Back
Close

Java Guild Meeting 5/2018

Gi11i4m
11.7K views

Streams

Kids, today we're going to learn about streams.

The code below doesn't use them. It transforms a list of names into a list of the same names but capitalized. See how much effort you have to put in to understand what the function actually does (well, imagining I didn't just tell you). That's thanks to all the boilerplate and non-declarative code. There's a garbage list with an annoying name that actually changes meaning since it's mutable, an ugly old for-loop, you have return your garbage list at the end and EVERYTHING IS AWFUL.

However there's a silver lining. You can easily make this code beautiful using Streams and its map operator. Operators mostly take lambda functions or function references. Check this page for docs. To start a Stream from an array of values, use the static Stream.of method. Don't forget to .collect() the results at the end to collect all the elements in a collection again. Why not return the stream itself? Good question, attentive reader. You certainly can. Whether it's a good idea depends on the context.

Rewrite this garbage using Streams and make sure the test still runs!
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants