Java HashMap putIfAbsent ()

Il metodo Java HashMap putIfAbsent () inserisce la mappatura chiave / valore specificata nell'hashmap se la chiave specificata non è già presente nell'hashmap.

La sintassi del putIfAbsent()metodo è:

 hashmap.putIfAbsent(K key, V value)

In questo caso, hashmap è un oggetto della HashMapclasse.

parametri putIfAbsent ()

Il putIfAbsent()metodo accetta due parametri.

  • chiave : il valore specificato è associato a questa chiave
  • valore : la chiave specificata viene mappata con questo valore

putAbsent () Valore restituito

  • restituisce il valore associato alla chiave, se la chiave specificata è già presente nella hashmap
  • restituisce null, se la chiave specificata non è già presente nella hashmap

Nota : se la chiave specificata è stata precedentemente associata a un valore null , anche il metodo restituisce null.

Esempio 1: Java HashMap putIfAbsent ()

 import java.util.HashMap; class Main ( public static void main(String() args)( // create a HashMap HashMap languages = new HashMap(); // add mappings to HashMap languages.put(1, "Python"); languages.put(2, "C"); languages.put(3, "Java"); System.out.println("Languages: " + languages); // key already not present in HashMap languages.putIfAbsent(4, "JavaScript"); // key already present in HashMap languages.putIfAbsent(2, "Swift"); System.out.println("Updated Languages: " + languages); ) )

Produzione

 Linguaggi: (1 = Python, 2 = C, 3 = Java) Linguaggi aggiornati: (1 = Python, 2 = C, 3 = Java, 4 = JavaScript)

Nell'esempio precedente, abbiamo creato una hashmap denominata languages. Notare la linea,

 languages.putIfAbsent(4, "JavaScript");

Qui, la chiave 4 non è già associata a nessun valore. Quindi, il putifAbsent()metodo aggiunge la mappatura (4 = JavaScript) alla hashmap.

Notare la linea,

 languages.putIfAbsent(2, "Swift");

Qui, la chiave 2 è già associata al valore Java. Quindi, il putIfAbsent()metodo non aggiunge la mappatura (2 = Swift) alla hashmap.

Nota : abbiamo utilizzato il put()metodo per aggiungere una singola mappatura alla hashmap. Per saperne di più, visita Java HashMap put ().

Articoli interessanti...