Example 3 (compute())

Let's suppose that we have the following Map:

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

We use this map to build JDBC URLs for different database types.

Let's assume that we want to build the JDBC URLs for MySQL and Derby DB. In this case, irrespective of whether the key (mysql or derby) is present in the map, the JDBC URL should be computed based on the corresponding key and value (which can be null). In addition, if the key is present in the map and the result of our computation is null (the JDBC URL cannot be computed), then we want to remove this entry from the map. Basically, this is a combination of computeIfPresent() and computeIfAbsent().

This is a job for V compute​(K key, BiFunction<? super K,​? super V,​? extends V> remappingFunction).

This time, BiFunction should be written to cover the case when the value of the searched key is null:

String address = InetAddress.getLocalHost().getHostAddress();
BiFunction<String, String, String> jdbcUrl = (k, v)
-> "jdbc:" + k + "://" + ((v == null) ? address : v)
+ "/customers_db";

Now, let's compute the JDBC URL for MySQL. Since the mysql key is present in the map, the computation will rely on the corresponding value, 192.168.0.50. The result will update the value of the mysql key in the map:

// jdbc:mysql://192.168.0.50/customers_db
String mysqlJdbcUrl = map.compute("mysql", jdbcUrl);

In addition, let's compute the JDBC URL for Derby DB. Since the derby key is not present in the map, the computation will rely on the current IP. The result will be added to the map under the derby key:

// jdbc:derby://192.168.100.10/customers_db
String derbyJdbcUrl = map.compute("derby", jdbcUrl);

After these two computations, the map will contain the following three entries:

  • postgresql=127.0.0.1
  • derby=jdbc:derby://192.168.100.10/customers_db
  • mysql=jdbc:mysql://192.168.0.50/customers_db
Pay attention to the fact that calling compute() again will recompute the values. This can lead to unwanted results such as jdbc:derby://jdbc:derby://....
If the result of the computation is null (for example, the JDBC URL cannot be computed) and the key (for example, mysql) exists in the map, then this entry will be removed from the map and the returned result is null.
..................Content has been hidden....................

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