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!
1
11
12
13
14
15
16
17
18
19
20
// {
public static Collection<String> mapToUppercase(String... names) {
Collection<String> uppercaseNames = new ArrayList<>();
for(String name : names) {
uppercaseNames.add(name.toUpperCase());
}
return uppercaseNames;
}
//{
1
// {
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.