Java HashMap replace() Example

Java HashMap has a replace() methods which enable programmers to replace.
  • entries.replace(K key, V value) - This method replaces the entry for the specified key only if it is currently mapped to some value.
  • replace(K key, V oldValue, V newValue) - This method replaces the entry for the specified key only if it is currently mapped to the specified value.

Java HashMap replace() Example

import java.util.HashMap;
import java.util.Map;

public class HashMapReplace {

    public static void main(String[] args) {

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

        capitals.put("day", "Monday");
        capitals.put("country", "Poland");
        capitals.put("colour", "blue");
        
        capitals.replace("day", "Sunday");
        capitals.replace("country", "Russia", "Great Britain");
        capitals.replace("colour", "blue", "green");

        capitals.entrySet().forEach(System.out::println);
    }
}

Output

country=Poland
colour=green
day=Sunday


Related HashMap Source Code Examples


Comments