Example 4 (merge())

Let's suppose that we have the following Map:

Map<String, String> map = new HashMap<>();
map.put("postgresql", "9.6.1 ");
map.put("mysql", "5.1 5.2 5.6 ");

We use this map to store the versions of each database type separated by a space.

Now, let's assume that every time a new version of a database type is released, we want to add it to our map under the corresponding key. If the key (for example, mysql) is present in the map, then we want to simply concatenate the new version to the end of the current value. If the key (for example, derby) is not present in the map, then we just want to add it now.

This is the perfect job for V merge​(K key, V value, BiFunction<? super V,​? super V,​? extends V> remappingFunction).

If the given key (K) is not associated with a value or is associated with null, then the new value will be V. If the given key (K) is associated with a non-null value, then the new value is computed based on the given BiFunction. If the result of this BiFunction is null, and the key is present in the map, then this entry will be removed from the map.

In our case, we want to concatenate the current value with the new version, so our BiFunction can be written as follows:

BiFunction<String, String, String> jdbcUrl = String::concat;

We have a similar situation with the following:

BiFunction<String, String, String> jdbcUrl 
= (vold, vnew) -> vold.concat(vnew);

For example, let's suppose that we want to concatenate in the map version 8.0 of MySQL. This can be accomplished as follows:

// 5.1 5.2 5.6 8.0
String mySqlVersion = map.merge("mysql", "8.0 ", jdbcUrl);

Later on, we concatenate version 9.0 as well:

// 5.1 5.2 5.6 8.0 9.0
String mySqlVersion = map.merge("mysql", "9.0 ", jdbcUrl);

Or, we add version 10.11.1.1 of Derby DB. This will result in a new entry in the map since there is no derby key present:

// 10.11.1.1
String derbyVersion = map.merge("derby", "10.11.1.1 ", jdbcUrl);

At the end of these three operations, the map entries will be as follows:

postgresql=9.6.1, derby=10.11.1.1, mysql=5.1 5.2 5.6 8.0 9.0
..................Content has been hidden....................

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