HashMap en Java con ejemplos

HashMap<K, V> es parte de la colección de Java desde Java 1.2. Esta clase se encuentra en el paquete java.util . Proporciona la implementación básica de la interfaz Map de Java. Almacena los datos en pares (clave, valor) y puede acceder a ellos mediante un índice de otro tipo (por ejemplo, un número entero). Un objeto se utiliza como clave (índice) para otro objeto (valor). Si intenta insertar la clave duplicada, reemplazará el elemento de la clave correspondiente.

HashMap es similar a HashTable , pero no está sincronizado. También permite almacenar las claves nulas, pero solo debe haber un objeto de clave nula y puede haber cualquier número de valores nulos. Esta clase no garantiza el orden del mapa. Para usar esta clase y sus métodos, debe importar el paquete java.util.HashMap o su superclase.

Java

// Java program to illustrate HashMap class of java.util
// package
  
// Importing HashMap class
import java.util.HashMap;
  
// Main class
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
        // Create an empty hash map by declaring object
        // of string and integer type
        HashMap<String, Integer> map = new HashMap<>();
  
        // Adding elements to the Map
        // using standard put() method
        map.put("vishal", 10);
        map.put("sachin", 30);
        map.put("vaibhav", 20);
  
        // Print size and content of the Map
        System.out.println("Size of map is:- "
                           + map.size());
  
        // Printing elements in object of Map
        System.out.println(map);
  
        // Checking if a key is present and if
        // present, print value by passing
        // random element
        if (map.containsKey("vishal")) {
  
            // Mapping
            Integer a = map.get("vishal");
  
            // Printing value fr the corresponding key
            System.out.println("value for key"
                               + " \"vishal\" is:- " + a);
        }
    }
}

Java

// Java program to Demonstrate the HashMap() constructor
  
// Importing basic required classes
import java.io.*;
import java.util.*;
  
// Main class
// To add elements to HashMap
class GFG {
  
    // Main driver method
    public static void main(String args[])
    {
        // No need to mention the
        // Generic type twice
        HashMap<Integer, String> hm1 = new HashMap<>();
  
        // Initialization of a HashMap using Generics
        HashMap<Integer, String> hm2
            = new HashMap<Integer, String>();
  
        // Adding elements using put method
        // Custom input elements
        hm1.put(1, "one");
        hm1.put(2, "two");
        hm1.put(3, "three");
  
        hm2.put(4, "four");
        hm2.put(5, "five");
        hm2.put(6, "six");
  
        // Print and display mapping of HashMap 1
        System.out.println("Mappings of HashMap hm1 are : "
                           + hm1);
  
        // Print and display mapping of HashMap 2
        System.out.println("Mapping of HashMap hm2 are : "
                           + hm2);
    }
}

Java

// Java program to Demonstrate
// HashMap(int initialCapacity) Constructor
  
// Importing basic classes
import java.io.*;
import java.util.*;
  
// Main class
// To add elements to HashMap
class AddElementsToHashMap {
  
    // Main driver method
    public static void main(String args[])
    {
        // No need to mention the
        // Generic type twice
        HashMap<Integer, String> hm1 = new HashMap<>(10);
  
        // Initialization of a HashMap using Generics
        HashMap<Integer, String> hm2
            = new HashMap<Integer, String>(2);
  
        // Adding elements to object of HashMap
        // using put method
  
        // HashMap 1
        hm1.put(1, "one");
        hm1.put(2, "two");
        hm1.put(3, "three");
  
        // HashMap 2
        hm2.put(4, "four");
        hm2.put(5, "five");
        hm2.put(6, "six");
  
        // Printing elements of HashMap 1
        System.out.println("Mappings of HashMap hm1 are : "
                           + hm1);
  
        // Printing elements of HashMap 2
        System.out.println("Mapping of HashMap hm2 are : "
                           + hm2);
    }
}

Java

// Java program to Demonstrate
// HashMap(int initialCapacity,float loadFactor) Constructor
  
// Importing basic classes
import java.io.*;
import java.util.*;
  
// Main class
// To add elements to HashMap
class GFG {
  
    // Main driver method
    public static void main(String args[])
    {
        // No need to mention the generic type twice
        HashMap<Integer, String> hm1
            = new HashMap<>(5, 0.75f);
  
        // Initialization of a HashMap using Generics
        HashMap<Integer, String> hm2
            = new HashMap<Integer, String>(3, 0.5f);
  
        // Add Elements using put() method
        // Custom input elements
        hm1.put(1, "one");
        hm1.put(2, "two");
        hm1.put(3, "three");
  
        hm2.put(4, "four");
        hm2.put(5, "five");
        hm2.put(6, "six");
  
        // Print and display elements in object of hashMap 1
        System.out.println("Mappings of HashMap hm1 are : "
                           + hm1);
  
        // Print and display elements in object of hashMap 2
        System.out.println("Mapping of HashMap hm2 are : "
                           + hm2);
    }
}

Java

// Java program to demonstrate the 
// HashMap(Map map) Constructor
  
import java.io.*;
import java.util.*;
  
class AddElementsToHashMap {
    public static void main(String args[])
    {
        // No need to mention the
        // Generic type twice
        Map<Integer, String> hm1 = new HashMap<>();
  
        // Add Elements using put method
        hm1.put(1, "one");
        hm1.put(2, "two");
        hm1.put(3, "three");
  
        // Initialization of a HashMap
        // using Generics
        HashMap<Integer, String> hm2
            = new HashMap<Integer, String>(hm1);
  
        System.out.println("Mappings of HashMap hm1 are : "
                           + hm1);
        
        System.out.println("Mapping of HashMap hm2 are : "
                           + hm2);
    }
}

Java

// Java program to add elements
// to the HashMap
  
import java.io.*;
import java.util.*;
  
class AddElementsToHashMap {
    public static void main(String args[])
    {
        // No need to mention the
        // Generic type twice
        HashMap<Integer, String> hm1 = new HashMap<>();
  
        // Initialization of a HashMap
        // using Generics
        HashMap<Integer, String> hm2
            = new HashMap<Integer, String>();
  
        // Add Elements using put method
        hm1.put(1, "Geeks");
        hm1.put(2, "For");
        hm1.put(3, "Geeks");
  
        hm2.put(1, "Geeks");
        hm2.put(2, "For");
        hm2.put(3, "Geeks");
  
        System.out.println("Mappings of HashMap hm1 are : "
                           + hm1);
        System.out.println("Mapping of HashMap hm2 are : "
                           + hm2);
    }
}

Java

// Java program to change
// elements of HashMap
  
import java.io.*;
import java.util.*;
class ChangeElementsOfHashMap {
    public static void main(String args[])
    {
  
        // Initialization of a HashMap
        HashMap<Integer, String> hm
            = new HashMap<Integer, String>();
  
        // Change Value using put method
        hm.put(1, "Geeks");
        hm.put(2, "Geeks");
        hm.put(3, "Geeks");
  
        System.out.println("Initial Map " + hm);
  
        hm.put(2, "For");
  
        System.out.println("Updated Map " + hm);
    }
}

Java

// Java program to remove
// elements from HashMap
  
import java.io.*;
import java.util.*;
class RemoveElementsOfHashMap{
    public static void main(String args[])
    {
        // Initialization of a HashMap
        Map<Integer, String> hm
            = new HashMap<Integer, String>();
  
        // Add elements using put method
        hm.put(1, "Geeks");
        hm.put(2, "For");
        hm.put(3, "Geeks");
        hm.put(4, "For");
  
        // Initial HashMap
        System.out.println("Mappings of HashMap are : "
                           + hm);
  
        // remove element with a key
        // using remove method
        hm.remove(4);
  
        // Final HashMap
        System.out.println("Mappings after removal are : "
                           + hm);
    }
}

Java

// Java program to traversal a
// Java.util.HashMap
  
import java.util.HashMap;
import java.util.Map;
  
public class TraversalTheHashMap {
    public static void main(String[] args)
    {
        // initialize a HashMap
        HashMap<String, Integer> map = new HashMap<>();
  
        // Add elements using put method
        map.put("vishal", 10);
        map.put("sachin", 30);
        map.put("vaibhav", 20);
  
        // Iterate the map using
        // for-each loop
        for (Map.Entry<String, Integer> e : map.entrySet())
            System.out.println("Key: " + e.getKey()
                               + " Value: " + e.getValue());
    }
}

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *