📜  Java中的 HashMap getOrDefault(key, defaultValue) 方法及示例

📅  最后修改于: 2022-05-13 01:54:53.202000             🧑  作者: Mango

Java中的 HashMap getOrDefault(key, defaultValue) 方法及示例

Map接口getOrDefault(Object key, V defaultValue)方法,由HashMap类实现,用于获取指定key映射的值。如果没有使用提供的键映射任何值,则返回默认值。

句法:

default V getOrDefault(Object key, V defaultValue)

参数:此方法接受两个参数:

  • key:这是必须获取其值的元素的
  • defaultValue:如果没有与指定键映射的值,则这是必须返回的默认值

返回值:此方法返回与指定键映射的,否则返回默认值

方案一:

// Java program to demonstrate
// getOrDefault(Object key, V defaultValue) method
  
import java.util.*;
  
public class GFG {
  
    // Main method
    public static void main(String[] args)
    {
  
        // Create a HashMap and add some values
        HashMap map
            = new HashMap<>();
        map.put("a", 100);
        map.put("b", 200);
        map.put("c", 300);
        map.put("d", 400);
  
        // print map details
        System.out.println("HashMap: "
                           + map.toString());
  
        // provide key whose value has to be obtained
        // and default value for the key. Store the
        // return value in k
        int k = map.getOrDefault("b", 500);
  
        // print the value of k returned by
        // getOrDefault(Object key, V defaultValue) method
        System.out.println("Returned Value: " + k);
    }
}
输出:
HashMap: {a=100, b=200, c=300, d=400}
Returned Value: 200

方案二:

// Java program to demonstrate
// getOrDefault(Object key, V defaultValue) method
  
import java.util.*;
  
public class GFG {
  
    // Main method
    public static void main(String[] args)
    {
  
        // Create a HashMap and add some values
        HashMap map
            = new HashMap<>();
        map.put("a", 100);
        map.put("b", 200);
        map.put("c", 300);
        map.put("d", 400);
  
        // print map details
        System.out.println("HashMap: "
                           + map.toString());
  
        // provide key whose value has to be obtained
        // and default value for the key. Store the
        // return value in k
        int k = map.getOrDefault("y", 500);
  
        // print the value of k returned by
        // getOrDefault(Object key, V defaultValue) method
        System.out.println("Returned Value: " + k);
    }
}
输出:
HashMap: {a=100, b=200, c=300, d=400}
Returned Value: 500

参考资料: https: Java/util/HashMap.html#getOrDefault-java.lang.Object-V-