Replacing a value in a Map in Java 8

The Java 8 SDK has a couple of interesting new default “replace” methods available on the Map interface.

Consider the following HashMap:

Map<String, String> sizes = new HashMap<>();
sizes.put("XS", "Extra small");
sizes.put("S", "Small");
sizes.put("M", "Medium");
sizes.put("L", "Large");
sizes.put("XL", "Extra large");
sizes.put("XXL", "Extra extra large");

Say we’d like to replace the value of key “S”:

String replacedValue = sizes.replace("S", "Small size");

The replace method returns the value of the replaced string. In the above case the key “S” will have a new value “Small size” and “replace” returns “Small” as it was the value of “S” before the replace operation.

What if we try to replace a non-existent key?

String replacedValue = sizes.replace("SX", "Small size");

replace will return null in this case and the map will remain untouched.

The replace method has an overload where you can specify the expected old value to be replaced:

boolean replaced = sizes.replace("S", "Small", "Small size");

This version of replace returns a boolean where a true answer means that the old value passed in for the key was in fact correct and it was replaced with the new value. The above code line returns true. The below code returns false and the map will remain untouched:

boolean replaced = sizes.replace("S", "hello", "Small size");

You can also easily replace all values in a map with the replaceAll method that accepts a function that in turn accepts a key and a value and returns the value that should replace all existing values in the map:

sizes.replaceAll((key, value) -> key.concat(" - ").concat(value));

Here’s what the map looks like after the replaceAll operation:

{S=S – Small, XL=XL – Extra large, XS=XS – Extra small, L=L – Large, M=M – Medium, XXL=XXL – Extra extra large}

View all posts related to Java here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: