Java Reference
In-Depth Information
There is also a way to perform this kind of manipulation on a Map instance, although you can only
change the value: the keys cannot be changed through these manipulation calls for the same reason that
replaceAll is hard for Set to implement. The method is still quite useful: consider, for instance, that we
want to execute a hygiene method on the featured book messages: we would like to clean up the messages
by providing a default message and remove trailing periods. We can do this by executing the replaceAll
method and returning the updated value, which we do in Listing 3-6. The complexity of this body does not
lend itself particularly nicely to a functional solution, so we went ahead with an inline function definition.
Listing 3-6. A Library instance method to clean up featured book messages using Map.replaceAll
/**
* Performs various clean-up tasks on all the features messages.
*/
public void cleanUpFeaturedMessages() {
this.getFeaturedBooks().replaceAll((book, msg) -> {
// Set a default message
if (msg == null || msg.isEmpty()) {
msg = "Featured " + book.getGenre().toString().toLowerCase() +
" book by " + book.getAuthor();
}
// Remove trailing periods unless they are an elipsis
if (msg.endsWith(".") && !msg.endsWith("...")) {
msg = msg.substring(0, msg.length() - 1);
}
return msg;
}
);
}
Map Computations
The Map class itself has been extended with some functional-style manipulations that allow you to work with
particular keys. These methods are not directly inspired by functional programming techniques, but rather
are shorthand for common code such as the following:
// Default values
String value = map.get(key);
if(value == null) {
value = computeValue(key);
map.put(key, value);
}
// Increment values
Integer value = map.get(key);
if(value != null) {
value += 1;
map.put(key, value);
}
 
Search WWH ::




Custom Search