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

14 Oct, 2019
HashMap Class Methods in Java with Examples | Set 1 (put(), get(), isEmpty() and size())
In this post more methods are discussed.
keySet(): java.util.HashMap.keySet() It returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.Syntax:
public Set keySet()
Return: a set view of the keys contained in this map

Syntax:
public Set keySet()
Return: a set view of the keys contained in this map

values(): java.util.HashMap.values() It returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa.Syntax:
public Collection values()
Return: a collection view of the values contained in 
this map

Syntax:
public Collection values()
Return: a collection view of the values contained in 
this map

containsKey(): java.util.HashMap.containsKey() It returns true if this map maps one or more keys to the specified value.Syntax:
public boolean containsValue(Object value)
Parameters:
value - value whose presence in this map is to be tested
Return: true if this map maps one or more keys to 
the specified value

Syntax:
public boolean containsValue(Object value)
Parameters:
value - value whose presence in this map is to be tested
Return: true if this map maps one or more keys to 
the specified value

Implementation:
// Java program illustrating usage of HashMap class methods// keySet(), values(), containsKey()import java.util.*;public class NewClass{    public static void main(String args[])    {        // 1   Creation of HashMap        HashMap<String, String> Geeks = new HashMap<>();          // 2   Adding values to HashMap as ("keys", "values")        Geeks.put("Language", "Java");        Geeks.put("Platform", "Geeks For geeks");        Geeks.put("Code", "HashMap");        Geeks.put("Learn", "More");          // 3  containsKey() method is to check the presence        //    of a particluar key        // Since 'Code' key present here, the condition is true        if (Geeks.containsKey("Code"))            System.out.println("Testing .containsKey : " +                                           Geeks.get("Code"));          // 4 keySet() method returns all the keys in HashMap        Set<String> Geekskeys = Geeks.keySet();        System.out.println("Initial keys  : " + Geekskeys);            // 5  values() method return all the values in HashMap        Collection<String> Geeksvalues = Geeks.values();        System.out.println("Initial values : " + Geeksvalues);          // Adding new set of key-value        Geeks.put("Search", "JavaArticle");          // Again using .keySet() and .values() methods        System.out.println("New Keys : " + Geekskeys);        System.out.println("New Values: " + Geeksvalues);    }}
Output:
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

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.

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

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.

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(), putIfAbsentimport 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
This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Akanksha_Rai
Java-Collections
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Stream In Java
Singleton Class in Java
Initializing a List in Java
Stack Class in Java
Introduction to Java
Initialize an ArrayList in Java