📜  Java HashMap

📅  最后修改于: 2020-10-12 10:03:20             🧑  作者: Mango

Java HashMap

Java HashMap类实现了Map接口,该接口允许我们存储键和值对,其中键应该是唯一的。如果尝试插入重复键,它将替换相应键的元素。使用键索引进行更新,删除等操作很容易。HashMap类位于java.util包中。

Java中的HashMap类似于旧式Hashtable类,但未同步。它也允许我们存储null元素,但是应该只有一个null键。从Java 5开始,它表示为HashMap ,其中K代表键,V代表值。它继承了AbstractMap类并实现Map接口。

要记住的要点

  • Java HashMap包含基于键的值。
  • Java HashMap仅包含唯一键。
  • Java HashMap可以具有一个null键和多个null值。
  • Java HashMap是不同步的。
  • Java HashMap不维护任何顺序。
  • Java HashMap类的初始默认容量为16,负载因子为0.75。

HashMap类的层次结构

如上图所示,HashMap类扩展了AbstractMap类并实现了Map接口。

HashMap类声明

我们来看一下java.util.HashMap类的声明。

public class HashMap extends AbstractMap implements Map, Cloneable, Serializable

HashMap类参数

让我们看一下java.util.HashMap类的参数。

  • K :这是此映射维护的键的类型。
  • V :这是映射值的类型。

Java HashMap类的构造方法

Constructor Description
HashMap() It is used to construct a default HashMap.
HashMap(Map m) It is used to initialize the hash map by using the elements of the given Map object m.
HashMap(int capacity) It is used to initializes the capacity of the hash map to the given integer value, capacity.
HashMap(int capacity, float loadFactor) It is used to initialize both the capacity and load factor of the hash map by using its arguments.

Java HashMap类的方法

Method Description
void clear() It is used to remove all of the mappings from this map.
boolean isEmpty() It is used to return true if this map contains no key-value mappings.
Object clone() It is used to return a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
Set entrySet() It is used to return a collection view of the mappings contained in this map.
Set keySet() It is used to return a set view of the keys contained in this map.
V put(Object key, Object value) It is used to insert an entry in the map.
void putAll(Map map) It is used to insert the specified map in the map.
V putIfAbsent(K key, V value) It inserts the specified value with the specified key in the map only if it is not already specified.
V remove(Object key) It is used to delete an entry for the specified key.
boolean remove(Object key, Object value) It removes the specified values with the associated specified keys from the map.
V compute(K key, BiFunction remappingFunction) It is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
V computeIfAbsent(K key, Function mappingFunction) It is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null.
V computeIfPresent(K key, BiFunction remappingFunction) It is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null.
boolean containsValue(Object value) This method returns true if some value equal to the value exists within the map, else return false.
boolean containsKey(Object key) This method returns true if some key equal to the key exists within the map, else return false.
boolean equals(Object o) It is used to compare the specified Object with the Map.
void forEach(BiConsumer action) It performs the given action for each entry in the map until all entries have been processed or the action throws an exception.
V get(Object key) This method returns the object that contains the value associated with the key.
V getOrDefault(Object key, V defaultValue) It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key.
boolean isEmpty() This method returns true if the map is empty; returns false if it contains at least one key.
V merge(K key, V value, BiFunction remappingFunction) If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V newValue) It replaces the old value with the new value for a specified key.
void replaceAll(BiFunction function) It replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
Collection values() It returns a collection view of the values contained in the map.
int size() This method returns the number of entries in the map.

Java HashMap示例

让我们看一个简单的HashMap示例来存储键和值对。

import java.util.*;
public class HashMapExample1{
 public static void main(String args[]){
   HashMap map=new HashMap();//Creating HashMap  
   map.put(1,"Mango");  //Put elements in Map
   map.put(2,"Apple");  
   map.put(3,"Banana"); 
   map.put(4,"Grapes"); 
 
   System.out.println("Iterating Hashmap...");
   for(Map.Entry m : map.entrySet()){  
    System.out.println(m.getKey()+" "+m.getValue());  
   }
}
}
Iterating Hashmap...
1 Mango
2 Apple
3 Banana
4 Grapes

在此示例中,我们将Integer作为键存储,将String作为值存储,因此我们使用HashMap作为类型。 put()方法将元素插入地图中。

要获取键和值元素,我们应该调用getKey()和getValue()方法。 Map.Entry接口包含getKey()和getValue()方法。但是,我们应该调用Map接口的entrySet()方法来获取Map.Entry的实例。

HashMap上没有重复的密钥

您不能在HashMap中存储重复的密钥。但是,如果您尝试将重复的密钥存储为另一个值,它将替换该值。

import java.util.*;
public class HashMapExample2{
 public static void main(String args[]){
   HashMap map=new HashMap();//Creating HashMap  
   map.put(1,"Mango");  //Put elements in Map
   map.put(2,"Apple");  
   map.put(3,"Banana"); 
   map.put(1,"Grapes"); //trying duplicate key
 
   System.out.println("Iterating Hashmap...");
   for(Map.Entry m : map.entrySet()){  
    System.out.println(m.getKey()+" "+m.getValue());  
   }
}
}
Iterating Hashmap...
1 Grapes
2 Apple
3 Banana

Java HashMap示例中的add()元素

在这里,我们看到了插入元素的不同方法。

import java.util.*;
class HashMap1{
 public static void main(String args[]){
   HashMap hm=new HashMap();  
System.out.println("Initial list of elements: "+hm);
  hm.put(100,"Amit");  
  hm.put(101,"Vijay");  
  hm.put(102,"Rahul"); 
 
  System.out.println("After invoking put() method ");
  for(Map.Entry m:hm.entrySet()){  
   System.out.println(m.getKey()+" "+m.getValue());  
  }
  
  hm.putIfAbsent(103, "Gaurav");
  System.out.println("After invoking putIfAbsent() method ");
  for(Map.Entry m:hm.entrySet()){  
   System.out.println(m.getKey()+" "+m.getValue());  
  }
  HashMap map=new HashMap();
  map.put(104,"Ravi");
  map.putAll(hm);
  System.out.println("After invoking putAll() method ");
  for(Map.Entry m:map.entrySet()){  
   System.out.println(m.getKey()+" "+m.getValue());  
  }
 }
}
Initial list of elements: {}
After invoking put() method 
100 Amit
101 Vijay
102 Rahul
After invoking putIfAbsent() method 
100 Amit
101 Vijay
102 Rahul
103 Gaurav
After invoking putAll() method 
100 Amit
101 Vijay
102 Rahul
103 Gaurav
104 Ravi

Java HashMap示例中的remove()元素

在这里,我们看到了删除元素的不同方法。

import java.util.*;
public class HashMap2 {
   public static void main(String args[]) {
  HashMap map=new HashMap();    
  map.put(100,"Amit");  
  map.put(101,"Vijay");  
  map.put(102,"Rahul");
  map.put(103, "Gaurav");
System.out.println("Initial list of elements: "+map);
//key-based removal
map.remove(100);
System.out.println("Updated list of elements: "+map);
//value-based removal
map.remove(101);
System.out.println("Updated list of elements: "+map);
//key-value pair based removal
map.remove(102, "Rahul");
System.out.println("Updated list of elements: "+map);
   }    
}

输出:

Initial list of elements: {100=Amit, 101=Vijay, 102=Rahul, 103=Gaurav}
Updated list of elements: {101=Vijay, 102=Rahul, 103=Gaurav}
Updated list of elements: {102=Rahul, 103=Gaurav}
Updated list of elements: {103=Gaurav}

Java HashMap示例替换()元素

在这里,我们看到了替换元素的不同方法。

import java.util.*;
class HashMap3{
 public static void main(String args[]){
   HashMap hm=new HashMap();  
  hm.put(100,"Amit");  
  hm.put(101,"Vijay");  
  hm.put(102,"Rahul"); 
  System.out.println("Initial list of elements:");
 for(Map.Entry m:hm.entrySet())
 {
System.out.println(m.getKey()+" "+m.getValue()); 
 }
 System.out.println("Updated list of elements:");
 hm.replace(102, "Gaurav");
 for(Map.Entry m:hm.entrySet())
 {
System.out.println(m.getKey()+" "+m.getValue()); 
 }
 System.out.println("Updated list of elements:");
 hm.replace(101, "Vijay", "Ravi");
 for(Map.Entry m:hm.entrySet())
 {
System.out.println(m.getKey()+" "+m.getValue()); 
 } 
 System.out.println("Updated list of elements:");
 hm.replaceAll((k,v) -> "Ajay");
 for(Map.Entry m:hm.entrySet())
 {
System.out.println(m.getKey()+" "+m.getValue()); 
 }
 }
}
Initial list of elements:
100 Amit
101 Vijay
102 Rahul
Updated list of elements:
100 Amit
101 Vijay
102 Gaurav
Updated list of elements:
100 Amit
101 Ravi
102 Gaurav
Updated list of elements:
100 Ajay
101 Ajay
102 Ajay

HashSet和HashMap之间的区别

HashSet仅包含值,而HashMap包含条目(键和值)。

Java HashMap示例:书籍

import java.util.*;  
class Book {  
int id;  
String name,author,publisher;  
int quantity;  
public Book(int id, String name, String author, String publisher, int quantity) {  
    this.id = id;  
    this.name = name;  
    this.author = author;  
    this.publisher = publisher;  
    this.quantity = quantity;  
}  
}  
public class MapExample {  
public static void main(String[] args) {  
    //Creating map of Books  
    Map map=new HashMap();  
    //Creating Books  
    Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);  
    Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);  
    Book b3=new Book(103,"Operating System","Galvin","Wiley",6);  
    //Adding Books to map 
    map.put(1,b1);
    map.put(2,b2);
    map.put(3,b3);
    
    //Traversing map
    for(Map.Entry entry:map.entrySet()){  
    int key=entry.getKey();
    Book b=entry.getValue();
        System.out.println(key+" Details:");
        System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity); 
    }  
}  
}  

输出:

1 Details:
101 Let us C Yashwant Kanetkar BPB 8
2 Details:
102 Data Communications and Networking Forouzan Mc Graw Hill 4
3 Details:
103 Operating System Galvin Wiley 6