Search code examples
javaspring-bootmaps

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.

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"); // key is "Brian", value is "some", new value will be "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.