Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I replace value of Map if the key is present?

I have this map:

Map<String, String> myMap = new HashMap<>();

I’m trying to check if this map has a key called "Brian". If – and only if – it does, I want to replace the value with "Hello".

If I understand correctly the computeIfPresent method does exactly that, but it expects a remappingFunction as the second parameter, and I just want to put in a simple value.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve tried this:

myMap.computeIfPresent("Brian", "Hello");

How do I do this?

>Solution :

Map<String, String> myMap = new HashMap<>();
myMap.put("Brian", "some");
System.out.println(myMap); // {Brian=some}
myMap.computeIfPresent("Brian", (key, value) -> "Hello");
System.out.println(myMap); // {Brian=Hello}

remappingFunction is a BinaryFunction (which can be short-written with lambda), accepting found map entry key and its value. And expecting you to tell the program, how to compute new value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading