Java Reference
In-Depth Information
List
<
String
>
result
=
Testing
.
elementFirstToUpperCaseLambdas
(
input
);
assertEquals
(
asList
(
"Ab"
),
result
);
}
Don't
use a lambda expression. I know that might appear to be strange advice in a topic
about how to use lambda expressions, but square pegs don't fit into round holes very well.
Having accepted this, we're bound to ask how we can still unit test our code and have the be-
nefit of lambda-enabled libraries.
Do
use method references. Any method that would have been written as a lambda expression
can also be written as a normal method and then directly referenced elsewhere in code using
method references.
In
Example 7-12
I've refactored out the lambda expression into its own method. This is then
used by the main method, which deals with converting the list of strings.
Example 7-12. Converting the first character to uppercase and applying it to a list
public
public static
static
List
<
String
>
elementFirstToUppercase
(
List
<
String
>
words
) {
return
return
words
.
stream
()
.
map
(
Testing:
:
firstToUppercase
)
.
collect
(
Collectors
.<
String
>
toList
());
}
public
public static
static
String
firstToUppercase
(
String value
) {
char
char
firstChar
=
Character
.
toUpperCase
(
value
.
charAt
(
0
));
return
return
firstChar
+
value
.
substring
(
1
);
}
Having extracted the method that actually performs string processing, we can cover all the
corner cases by testing that method on its own. The same test case in its new, simplified form
is shown in
Example 7-13
.
Example 7-13. The two-character test applied to a single method
@Test
public
public
void
void
twoLetterStringConvertedToUppercase
() {
String input
=
"ab"
;
String result
=
Testing
.
firstToUppercase
(
input
);
assertEquals
(
"Ab"
,
result
);
}