Here the example Meaning HashMap getOrDefault(key, defaultValue) method in Javacoding

The getOrDefault(Object key, V defaultValue) technique of Map interface, applied by HashMap class is used to get the worth mapped with specified key. If no worth is mapped with the offered key then the default worth is returned.

Syntax:

Attention reader! Don’t cease studying now. Get maintain of all of the essential Java Foundation and Collections ideas with the Fundamentals of Java and Java Collections Course at a student-friendly value and grow to be business prepared. To full your preparation from studying a language to DS Algo and plenty of extra,  please refer Complete Interview Preparation Course.

default V getOrDefault(Object key, V defaultValue)

Parameters: This technique accepts two parameters:

  • key: which is the key of the ingredient whose worth needs to be obtained.
  • defaultValue: which is the default worth that needs to be returned, if no worth is mapped with the desired key.

Return Value: This technique returns worth mapped with the desired key, in any other case default worth is returned.

Program 1:

 

import java.util.*;

 

public class GFG {

 

    

    public static void main(String[] args)

    

 

        

        HashMap<String, Integer> map

            = new HashMap<>();

        map.put("a", 100);

        map.put("b", 200);

        map.put("c", 300);

        map.put("d", 400);

 

        

        System.out.println("HashMap: "

                           + map.toString());

 

        

        

        

        int ok = map.getOrDefault("b", 500);

 

        

        

        System.out.println("Returned Value: " + ok);

    

}

Output:

HashMap: {a=100, b=200, c=300, d=400}
Returned Value: 200

Program 2:

 

import java.util.*;

 

public class GFG {

 

    

    public static void main(String[] args)

    

 

        

        HashMap<String, Integer> map

            = new HashMap<>();

        map.put("a", 100);

        map.put("b", 200);

        map.put("c", 300);

        map.put("d", 400);

 

        

        System.out.println("HashMap: "

                           + map.toString());

 

        

        

        

        int ok = map.getOrDefault("y", 500);

 

        

        

        System.out.println("Returned Value: " + ok);

    

}

Output:

HashMap: {a=100, b=200, c=300, d=400}
Returned Value: 500

References: https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#getOrDefault-java.lang.Object-V-

Add a Comment

Your email address will not be published.