JDK8新增getOrDefault使用方法

上源码
在这里插入图片描述
Method Returns
The getOrDefault() method returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

直译一下就是当HashMap集合中有这个key时,如果存在则return it,如果没有就使用默认值defaultValue

举例

  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 k = map.getOrDefault("b", 500); 

    System.out.println("Returned Value: " + k); 
} 
//输出
HashMap: {a=100, b=200, c=300, d=400}
Returned Value: 200

示例2


```java
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 k = map.getOrDefault("y", 500); 
  

        System.out.println("Returned Value: " + k); 
        //输出
        HashMap: {a=100, b=200, c=300, d=400}
        Returned Value: 500

发布了26 篇原创文章 · 获赞 1 · 访问量 486

猜你喜欢

转载自blog.csdn.net/Vince_Wang1/article/details/103868451
今日推荐