HashMap类的computeIfAbsent(Key,Function)方法,如果key尚未与value关联(或映射为null),则通过指定映射函数生成key的value。

public V  computeIfAbsent(K key, Function<? super K, ? extends V> remappingFunction)

参数

key:与值关联的键。
remappingFunction:对值进行操作的函数。

返回:此方法返回与指定键关联的当前(现有或计算)值,如果映射返回null,则返回null。

  • 如果此方法的映射函数返回null,则不记录映射。
  • 如果重映射函数抛出异常,则重新抛出异常,并不记录映射。
  • 在计算过程中,不允许使用此方法修改此映射。
  • 如果重映射函数在计算期间修改了此映射,则此方法将抛出ConcurrentModificationException。 
import java.util.*; 
  
public class GFG { 
  
    // Main method 
    public static void main(String[] args) 
    { 
  

        Map<String, Integer> map = new Hashtable<>(); 
        map.put("Pen", 10); 
        map.put("Book", 500); 
        map.put("Clothes", 400); 
        map.put("Mobile", 5000); 
  
        System.out.println("hashTable: "
                           + map.toString()); 
  
        // 为缺少的新key提供值
        // 使用computeIfAbsent方法
        map.computeIfAbsent("newPen", k -> 600); 
        map.computeIfAbsent("newBook", k -> 800); 
         
        System.out.println("new hashTable: "
                           + map); 
    } 
} 

输出

hashTable:{Book = 500,Mobile = 5000,Pen = 10,Clothes = 400}
new hashTable:{newPen = 600,Book = 500,newBook = 800,Mobile = 5000,Pen = 10,Clothes = 400}  

import java.util.*; 
  
public class GFG { 
  
    // Main method 
    public static void main(String[] args) 
    { 
  
        Map<Integer, String> map = new Hashtable<>(); 
        map.put(1, "100RS"); 
        map.put(2, "500RS"); 
        map.put(3, "1000RS"); 
  
        System.out.println("hashTable: "
                           + map.toString()); 
  
        // 不存在健值对的情况
        // 使用computeIfAbsent方法
        map.computeIfAbsent(4, k -> "600RS"); 
  
        // 如果存在不会有任何影响
        // key为1已经存在了 
        map.computeIfAbsent(1, k -> "800RS"); 
  
        System.out.println("new hashTable: "
                           + map); 
    } 
} 

输出

hashTable:{3 = 1000RS,2 = 500RS,1 = 100RS}
new hashTable:{4 = 600RS,3 = 1000RS,2 = 500RS,1 = 100RS}

推荐文档

相关文档

大家感兴趣的内容

随机列表