Open In App

Hashmap methods in Java with Examples | Set 2 (keySet(), values(), containsKey()..)

HashMap Class Methods in Java with Examples | Set 1 (put(), get(), isEmpty() and size())

In this post more methods are discussed.



Testing .containsKey : HashMap
Initial keys  : [Language, Platform, Learn, Code]
Initial values : [Java, Geeks For geeks, More, HashMap]
New Keys : [Language, Platform, Search, Learn, Code]
New Values: [Java, Geeks For geeks, JavaArticle, More, HashMap]
  • .entrySet() : java.util.HashMap.entrySet() method returns a complete set of keys and values present in the HashMap.
    Syntax:
    public Set<Map.Entry> entrySet()
    Return:
    complete set of keys and values
    
  • .getOrDefault : java.util.HashMap.getOrDefault() method returns a default value if there is no value find using the key we passed as an argument in HashMap. If the value for key if present already in the HashMap, it won’t do anything to it.
    It is very nice way to assign values to the keys that are not yet mapped, without interfering with the already present set of keys and values.
    Syntax:
    default V getOrDefault(Object key,V defaultValue)
    Parameters:
    key - the key whose mapped value we need to return
    defaultValue - the default for the keys present in HashMap
    Return:
    mapping the unmapped keys with the default value.
    
  • .replace() : java.util.HashMap.replace(key, value) or java.util.HashMap.replace(key, oldvalue, newvalue) method is a java.util.HashMap class method.
    1st method accepts set of key and value which will replace the already present value of the key with the new value passed in the argument. If no such set is present replace() method will do nothing.
    Meanwhile 2nd method will only replace the already present set of key-old_value if the key and old_Value are found in the HashMap.
    Syntax:
    replace(k key, v value)
              or
    replace(k key, v oldvalue, newvalue)
    Parameters:
    key      - key in set with the old value.
    value    - new value we want to be with the specified key
    oldvalue - old value in set with the specified key
    newvalue - new value we want to be with the specified key
    Return:
    True - if the value is replaced
    Null - if there is no such set present
    
  • .putIfAbsent java.util.HashMap.putIfAbsent(key, value) method is being used to insert a new key-value set to the HashMap if the respective set is present. Null value is returned if such key-value set is already present in the HashMap.
    Syntax:
    public V putIfAbsent(key, value)
    Parameters:
    key      - key with which the specified value is associates.
    value    - value to associates with the specified key.
    



  • // Java Program illustrating HashMap class methods(). 
    // entrySet(), getOrDefault(), replace(), putIfAbsent
    import java.util.*;
    public class NewClass
    {
        public static void main(String args[])
        {
            // Creation of HashMap
            HashMap<String, String> Geeks = new HashMap<>();
      
            // Adding values to HashMap as ("keys", "values")
            Geeks.put("Language", "Java");
            Geeks.put("Code", "HashMap");
            Geeks.put("Learn", "More");
      
            // .entrySet() returns all the keys with their values present in Hashmap
            Set<Map.Entry<String, String>> mappingGeeks = Geeks.entrySet();
            System.out.println("Set of Keys and Values using entrySet() : "+mappingGeeks);
            System.out.println();
      
            // Using .getOrDefault to access value
            // Here it is Showing Default value as key - "Code" was already present
            System.out.println("Using .getorDefault : " 
                                        + Geeks.getOrDefault("Code","javaArticle"));
      
            // Here it is Showing set value as key - "Search" was not present
            System.out.println("Using .getorDefault : "
                                        + Geeks.getOrDefault("Search","javaArticle"));
            System.out.println();
      
            // .replace() method replacing value of key "Learn"
            Geeks.replace("Learn", "Methods");
            System.out.println("working of .replace()     : "+mappingGeeks);
            System.out.println();
      
            /* .putIfAbsent() method is placing a new key-value
                as they were not present initially*/
            Geeks.putIfAbsent("cool", "HashMap methods");
            System.out.println("working of .putIfAbsent() : "+mappingGeeks);
      
            /* .putIfAbsent() method is not doing anything
                as key-value were already present */
            Geeks.putIfAbsent("Code", "With_JAVA");
            System.out.println("working of .putIfAbsent() : "+mappingGeeks);
      
        }
    }
    
    

    Output:

    Set of Keys and Values using entrySet() : [Language=Java, Learn=More, Code=HashMap]
    
    Using .getorDefault : HashMap
    Using .getorDefault : javaArticle
    
    working of .replace()     : [Language=Java, Learn=Methods, Code=HashMap]
    
    working of .putIfAbsent() : [Language=Java, cool=HashMap methods, Learn=Methods, Code=HashMap]
    working of .putIfAbsent() : [Language=Java, cool=HashMap methods, Learn=Methods, Code=HashMap]
    
  • remove(Object key): Removes the mapping for this key from this map if present.



  • // Java Program illustrating remove() method using Iterator.
      
    import java.util.*;
    public class NewClass
    {
        public static void main(String args[])
        {
            //  Creation of HashMap
            HashMap<String, String> Geeks = new HashMap<>();
      
            //  Adding values to HashMap as ("keys", "values")
            Geeks.put("Language", "Java");
            Geeks.put("Platform", "Geeks For geeks");
            Geeks.put("Code", "HashMap");
      
      
            //  .entrySet() returns all the keys with their values present in Hashmap
            Set<Map.Entry<String, String>> mappingGeeks = Geeks.entrySet();
            System.out.println("Set of Keys and Values : "+mappingGeeks);
            System.out.println();
      
            //  Creating an iterator
            System.out.println("Use of Iterator to remove the sets.");
            Iterator<Map.Entry<String, String>> geeks_iterator = Geeks.entrySet().iterator();
            while(geeks_iterator.hasNext())
            {
                Map.Entry<String, String> entry = geeks_iterator.next();
                //  Removing a set one by one using iterator
                geeks_iterator.remove(); // right way to remove entries from Map,
                // avoids ConcurrentModificationException
                System.out.println("Set of Keys and Values : "+mappingGeeks);
      
            }
        }
    }
    
    

    Output:

    Set of Keys and Values : [Language=Java, Platform=Geeks For geeks, Code=HashMap]
    
    Use of Iterator to remove the sets.
    Set of Keys and Values : [Platform=Geeks For geeks, Code=HashMap]
    Set of Keys and Values : [Code=HashMap]
    Set of Keys and Values : []
    

    Advantage:
    If we use for loop, it get translated to Iterator internally but without using Iterator explicitly we can’t remove any entry during Iteration.On doing so, Iterator may throw ConcurrentModificationException. So, we use explicit Iterator and while loop to traverse.

    Reference:
    https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html


    Article Tags :