W tym samouczku dowiemy się o klasie Java HashMap i jej różnych operacjach na przykładach.
HashMap
Klasa zbiorów ramach Java zapewnia funkcjonalność struktury danych tabeli hash.
Przechowuje elementy w parach klucz / wartość . Tutaj klucze są unikalnymi identyfikatorami używanymi do kojarzenia każdej wartości na mapie.
HashMap
Klasa implementuje interfejs Map.

Utwórz HashMap
Aby utworzyć mapę skrótów, musimy najpierw zaimportować java.util.HashMap
pakiet. Po zaimportowaniu pakietu, oto jak możemy tworzyć hashmapy w Javie.
// hashMap creation with 8 capacity and 0.6 load factor HashMap numbers = new HashMap();
W powyższym kodzie utworzyliśmy hashmap o nazwie liczby. Tutaj K reprezentuje typ klucza, a V reprezentuje typ wartości. Na przykład,
HashMap numbers = new HashMap();
Tutaj typ kluczy to, String
a typ wartości to Integer
.
Przykład 1: Utwórz HashMap w Javie
import java.util.HashMap; class Main ( public static void main(String() args) ( // create a hashmap HashMap languages = new HashMap(); // add elements to hashmap languages.put("Java", 8); languages.put("JavaScript", 1); languages.put("Python", 3); System.out.println("HashMap: " + languages); ) )
Wynik
HashMap: (Java = 8, JavaScript = 1, Python = 3)
W powyższym przykładzie utworzyliśmy HashMap
nazwane języki.
Tutaj użyliśmy tej put()
metody, aby dodać elementy do tablicy mieszania. Dowiemy się więcej o tej put()
metodzie w dalszej części tego samouczka.
Podstawowe operacje na Java HashMap
HashMap
Klasa udostępnia różne metody do wykonywania różnych operacji na hashmaps. W tym samouczku przyjrzymy się niektórym powszechnie używanym operacjom arraylist:
- Dodaj elementy
- Dostęp do elementów
- Zmień elementy
- Usuń elementy
1. Dodaj elementy do HashMap
Aby dodać pojedynczy element do hashmap, używamy put()
metody HashMap
klasy. Na przykład,
import java.util.HashMap; class Main ( public static void main(String() args) ( // create a hashmap HashMap numbers = new HashMap(); System.out.println("Initial HashMap: " + numbers); // put() method to add elements numbers.put("One", 1); numbers.put("Two", 2); numbers.put("Three", 3); System.out.println("HashMap after put(): " + numbers); ) )
Wynik
Initial HashMap: () HashMap po put (): (One = 1, Two = 2, Three = 3)
W powyższym przykładzie utworzyliśmy HashMap
nazwane liczby. Tutaj zastosowaliśmy put()
metodę dodawania elementów do liczb.
Zwróć uwagę na oświadczenie,
numbers.put("One", 1);
Tutaj przekazujemy String
wartość One jako klucz i Integer
wartość 1 jako wartość do put()
metody.
Zalecane lektury
- Java HashMap put ()
- Java HashMap putAll ()
- Java HashMap putIfAbsent ()
2. Uzyskaj dostęp do elementów HashMap
Możemy użyć tej get()
metody, aby uzyskać dostęp do wartości z tablicy mieszania. Na przykład,
import java.util.HashMap; class Main ( public static void main(String() args) ( HashMap languages = new HashMap(); languages.put(1, "Java"); languages.put(2, "Python"); languages.put(3, "JavaScript"); System.out.println("HashMap: " + languages); // get() method to get value String value = languages.get(1); System.out.println("Value at index 1: " + value); ) )
Wynik
HashMap: (1 = Java, 2 = Python, 3 = JavaScript) Wartość w indeksie 1: Java
W powyższym przykładzie zwróć uwagę na wyrażenie
languages.get(1);
W tym przypadku get()
metoda przyjmuje klucz jako argument i zwraca odpowiednią wartość skojarzoną z kluczem.
Możemy również uzyskać dostęp do kluczy , wartości i klucz / wartość pary hashmap jak ustawić za pomocą widoków keySet()
, values()
oraz entrySet()
metod odpowiednio. Na przykład,
import java.util.HashMap; class Main ( public static void main(String() args) ( HashMap languages = new HashMap(); languages.put(1, "Java"); languages.put(2, "Python"); languages.put(3, "JavaScript"); System.out.println("HashMap: " + languages); // return set view of keys // using keySet() System.out.println("Keys: " + languages.keySet()); // return set view of values // using values() System.out.println("Values: " + languages.values()); // return set view of key/value pairs // using entrySet() System.out.println("Key/Value mappings: " + languages.entrySet()); ) )
Wynik
HashMap: (1 = Java, 2 = Python, 3 = JavaScript) Klucze: (1, 2, 3) Wartości: (Java, Python, JavaScript) Mapowania klucza / wartości: (1 = Java, 2 = Python, 3 = JavaScript )
W powyższym przykładzie utworzyliśmy hashmap o nazwie języki. Tutaj uzyskujemy dostęp do kluczy , wartości i mapowań klucz / wartość z tablicy mieszania.
Zalecane lektury
- Java HashMap get ()
- Java Hashmap getOrDefault ()
- Zestaw kluczy Java HashMap ()
- Wartości Java HashMap ()
- Java HashMap entrySet ()
3. Zmień wartość HashMap
Możemy użyć tej replace()
metody, aby zmienić wartość związaną z kluczem w tablicy mieszającej. Na przykład,
import java.util.HashMap; class Main ( public static void main(String() args) ( HashMap languages = new HashMap(); languages.put(1, "Java"); languages.put(2, "Python"); languages.put(3, "JavaScript"); System.out.println("Original HashMap: " + languages); // change element with key 2 languages.replace(2, "C++"); System.out.println("HashMap using replace(): " + languages); ) )
Wynik
Oryginalna mapa HashMap: (1 = Java, 2 = Python, 3 = JavaScript) HashMap przy użyciu replace (): (1 = Java, 2 = C ++, 3 = JavaScript)
W powyższym przykładzie utworzyliśmy hashmap o nazwie języki. Zwróć uwagę na wyrażenie,
languages.replace(2, "C++");
Tutaj zmieniamy wartość, do której odwołuje się klucz 2, na nową wartość C ++.
HashMap
Klasa przewiduje również pewne odmiany replace()
metody. Aby dowiedzieć się więcej, odwiedź
- Zamiana Java HashMap ()
- Java HashMap replaceAll ()
4. Usuń elementy HashMap
Aby usunąć elementy z hashmap, możemy użyć metody remove (). Na przykład,
import java.util.HashMap; class Main ( public static void main(String() args) ( HashMap languages = new HashMap(); languages.put(1, "Java"); languages.put(2, "Python"); languages.put(3, "JavaScript"); System.out.println("HashMap: " + languages); // remove element associated with key 2 String value = languages.remove(2); System.out.println("Removed value: " + value); System.out.println("Updated HashMap: " + languages); ) )
Wynik
HashMap: (1 = Java, 2 = Python, 3 = JavaScript) Usunięta wartość: Python Zaktualizowany HashMap: (1 = Java, 3 = JavaScript)
Tutaj remove()
metoda przyjmuje klucz jako parametr. Następnie zwraca wartość skojarzoną z kluczem i usuwa wpis .
Możemy również usunąć wpis tylko pod pewnymi warunkami. Na przykład,
remove(2, "C++");
Here, the remove()
method only removes the entry if the key 2 is associated with the value C++. Since 2 is not associated with C++, it doesn't remove the entry.
To learn more, visit Java HashMap remove().
Other Methods of HashMap
Method | Description |
---|---|
clear() | removes all mappings from the HashMap |
compute() | computes a new value for the specified key |
computeIfAbsent() | computes value if a mapping for the key is not present |
computeIfPresent() | computes a value for mapping if the key is present |
merge() | merges the specified mapping to the HashMap |
clone() | makes the copy of the HashMap |
containsKey() | checks if the specified key is present in Hashmap |
containsValue() | checks if Hashmap contains the specified value |
size() | returns the number of items in HashMap |
isEmpty() | checks if the Hashmap is empty |
Iterate through a HashMap
To iterate through each entry of the hashmap, we can use Java for-each loop. We can iterate through keys only, vales only, and key/value mapping. For example,
import java.util.HashMap; import java.util.Map.Entry; class Main ( public static void main(String() args) ( // create a HashMap HashMap languages = new HashMap(); languages.put(1, "Java"); languages.put(2, "Python"); languages.put(3, "JavaScript"); System.out.println("HashMap: " + languages); // iterate through keys only System.out.print("Keys: "); for (Integer key : languages.keySet()) ( System.out.print(key); System.out.print(", "); ) // iterate through values only System.out.print("Values: "); for (String value : languages.values()) ( System.out.print(value); System.out.print(", "); ) // iterate through key/value entries System.out.print("Entries: "); for (Entry entry : languages.entrySet()) ( System.out.print(entry); System.out.print(", "); ) ) )
Output
HashMap: (1=Java, 2=Python, 3=JavaScript) Keys: 1, 2, 3, Values: Java, Python, JavaScript, Entries: 1=Java, 2=Python, 3=JavaScript,
Note that we have used the Map.Entry
in the above example. It is the nested class of the Map
interface that returns a view (elements) of the map.
We first need to import the java.util.Map.Entry
package in order to use this class.
This nested class returns a view (elements) of the map.
Creating HashMap from Other Maps
In Java, we can also create a hashmap from other maps. For example,
import java.util.HashMap; import java.util.TreeMap; class Main ( public static void main(String() args) ( // create a treemap TreeMap evenNumbers = new TreeMap(); evenNumbers.put("Two", 2); evenNumbers.put("Four", 4); System.out.println("TreeMap: " + evenNumbers); // create hashmap from the treemap HashMap numbers = new HashMap(evenNumbers); numbers.put("Three", 3); System.out.println("HashMap: " + numbers); ) )
Output
TreeMap: (Four=4, Two=2) HashMap: (Two=2, Three=3, Four=4)
In the above example, we have created a TreeMap
named evenNumbers
. Notice the expression,
numbers = new HashMap(evenNumbers)
Here, we are creating a HashMap
named numbers using the TreeMap
. To learn more about treemap, visit Java TreeMap.
Note: While creating a hashmap, we can include optional parameters: capacity and load factor. For example,
HashMap numbers = new HashMap(8, 0.6f);
Here,
- 8 (capacity is 8) - This means it can store 8 entries.
- 0.6f (load factor is 0.6) - This means whenever our hash table is filled by 60%, the entries are moved to a new hash table double the size of the original hash table.
Jeśli opcjonalne parametry nie są używane, domyślna pojemność będzie wynosić 16, a domyślny współczynnik obciążenia będzie równy 0,75 .