Java Reference
In-Depth Information
public
public Artist getArtist ( String name ) {
Artist artist = artistCache . get ( name );
iif ( artist == null
null ) {
artist = readArtistFromDB ( name );
artistCache . put ( name , artist );
}
return
return artist ;
}
Java 8 introduces a new computeIfAbsent method that takes a lambda to compute the new
value if it doesn't already exist. So, we can rewrite the previous block of code into
Example 5-32 .
Example 5-32. Caching a value using computeIfAbsent
public
public Artist getArtist ( String name ) {
return
return artistCache . computeIfAbsent ( name , this
this :: readArtistFromDB );
}
You may want variants of this code that don't perform computation only if the value is ab-
sent; the new compute and computeIfPresent methods on the Map interface are useful for
these cases.
At some point in your career, you might have tried to iterate over a Map . Historically, the ap-
proach was to use the values method to get a Set of entries and then iterate over them. This
tended to result in fairly hard-to-read code. Example 5-33 shows an approach from earlier in
the chapter of creating a new Map counting the number of albums associated with each artist.
Example 5-33. An ugly way to iterate over all entries of a Map
Map < Artist , Integer > countOfAlbums = new
new HashMap <>();
for
for ( Map . Entry < Artist , List < Album >> entry : albumsByArtist . entrySet ()) {
Artist artist = entry . getKey ();
List < Album > albums = entry . getValue ();
countOfAlbums . put ( artist , albums . size ());
}
Thankfully, a new forEach method has been introduced that takes a BiConsumer (two values
enter, nothing leaves) and produces easier-to-read code through internal iteration, which I in-
troduced in From External Iteration to Internal Iteration . An equivalent code sample is shown
in Example 5-34 .
Example 5-34. Using internal iteration over all entries of a Map
Search WWH ::




Custom Search