Example 1 (computeIfPresent())

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 URL for MySQL. If the mysql key is present in the map, then the JDBC URL should be computed based on the corresponding value, jdbc:mysql://192.168.0.50/customers_db. But if the mysql key is not present, then the JDBC URL should be null. In addition to this, if the result of our computation is null (the JDBC URL cannot be computed), then we want to remove this entry from the map.

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

In our case, BiFunction used for computing the new value will be as follows (k is the key from the map, v is the value associated with the key):

BiFunction<String, String, String> jdbcUrl 
= (k, v) -> "jdbc:" + k + "://" + v + "/customers_db";

Once we have this function in place, we can compute the new value for the mysql key as follows:

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

Since the mysql key is present in the map, the result will be jdbc:mysql://192.168.0.50/customers_db, and the new map contains the following entries:

postgresql=127.0.0.1, mysql=jdbc:mysql://192.168.0.50/customers_db
Calling computeIfPresent() again will recompute the value, which means that it will result in something like mysql= jdbc:mysql://jdbc:mysql://.... Obviously, this is not OK, so pay attention to this aspect.

On the other hand, if we try the same computation for an entry that doesn't exist (for example, voltdb), then the returned value will be null and the map remains untouched:

// null
String voldDbJdbcUrl = map.computeIfPresent("voltdb", jdbcUrl);
..................Content has been hidden....................

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