Example 2 (computeIfAbsent())

Let's suppose that we have the following Map:

Map<String, String> map = new HashMap<>();
map.put("postgresql", "jdbc:postgresql://127.0.0.1/customers_db");
map.put("mysql", "jdbc:mysql://192.168.0.50/customers_db");

We use this map to build JDBC URLs for different databases.

Let's assume that we want to build the JDBC URL for MongoDB. This time, if the mongodb key is present in the map, then the corresponding value should be returned without further computations. But if this key is absent (or is associated with a null value), then it should be computed based on this key and the current IP and be added to the map. If the computed value is null, then null is the returned result and the map remains untouched.

Well, this is a job for V computeIfAbsent​(K key, Function<? super K,​? extends V> mappingFunction).

In our case, Function used to compute the value will be as follows (the first String is the key from the map (k), while the second String is the value computed for this key):

String address = InetAddress.getLocalHost().getHostAddress();

Function<String, String> jdbcUrl
= k -> k + "://" + address + "/customers_db";

Based on this function, we can try to obtain the JDBC URL for MongoDB via the mongodb key as follows:

// mongodb://192.168.100.10/customers_db
String mongodbJdbcUrl = map.computeIfAbsent("mongodb", jdbcUrl);

Since our map doesn't contain the mongodb key, it will be computed and added to the map.

If our Function is evaluated to null, then the map remains untouched and the returned value is null.

Calling computeIfAbsent() again will not recompute the value. This time, since mongodb is in the map (it was added at the previous call), the returned value will be mongodb://192.168.100.10/customers_db. This is the same as trying to fetch the JDBC URL for mysql, which will return jdbc:mysql://192.168.0.50/customers_db without further computations.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset