HashMap in Java

HashMap in Java

Underlying data structure of HashMap is hash-table in java.

Insertion order is not preserved and it is based on hashcode of keys .

Duplicates keys are not allowed but values can be duplicated.

Heterogeneous object are allowed for both key and value.

Null is allowed for keys(only once )

Null is allowed for values (any number of times).

HashMap implements serializable and clonable interfaces but not random access.

HashMap is choice if our frequent operation is search opration

Java HashMap is not thread-safe. You must explicitly synchronize concurrent modifications to the HashMap.

HashMap Constructor:

HashMap m= new HashMap();

Creates an empty HashMap object with default initialCapacity 16 and default fillRatio 0.75 .

HashMap m= new HashMap(int initialCapacity);

Creates an empty HashMap object with specified initial capacity .

HashMap m= new HashMap(int initialCapacity,float fillRatio);

Creates an empty HashMap object with specified initial capacity and default ratio 0.75

HashMap m= new HashMap(Map m);

Convert any Map object to HashMap using this constructor.

Creating a HashMap and Adding key-value pairs to it

Following Example Demonstrate how to create a HashMap, and add new key-value pairs to it.

import java.util.HashMap;

import java.util.Map;

public class HashMapExample1 {

    public static void main(String[] args) {

        // Creating a HashMap

        Map<String, String> stateMapping = new HashMap<>();

        // Adding key-value pairs to a HashMap

        stateMapping.put(“Maharastra”, “Mumbai”);

        stateMapping.put(“Goa”, “Panji”);

        stateMapping.put(“Telangana”, “Hyderabad”);

                   stateMapping.put(“Hariyana”, “Chandigarh”);

        // Add a new key-value pair only if the key does not exist in the HashMap, or is mapped to `null`

        stateMapping.putIfAbsent(“Panjab”,”Chandigarh” );

        System.out.println(stateMapping);

    }

}

output:

{Panjab=Chandigarh, Hariyana=Chandigarh, Telangana=Hyderabad, Goa=Panji, Maharastra=Mumbai}

Accessing keys and modifying their associated value in a HashMap

We will demonstate the following methods on the programatically below example.

isEmpty(): to check if a HashMap is empty.

 size():  to find the size of a HashMap.

containsKey(): to check if a given key exists in a HashMap.

containsValue(): to check if a given value exists in a HashMap. 

get(): to get the value associated with a given key in the HashMap.

put(): to modify the value associated with a given key in the HashMap.

import java.util.HashMap;
 import java.util.Map;
 public class AccessKeysHashMapExample {
     public static void main(String[] args) {
         Map customerCity = new HashMap<>();
           // Check if a HashMap is empty
         System.out.println("is customerCity empty? : " + customerCity.isEmpty()); 
         customerCity.put("Ganesh", "Pune");
         customerCity.put("Balaji", "Bengaluru");
         customerCity.put("Pawan", "Hyderabad"); 
         System.out.println("customerCity HashMap : " + customerCity);
         // Find the size of a HashMap
         System.out.println("We have the city information of " + customerCity.size() + " users");  
        
         String customerName = "Uday"; 
         // Check if a key exists in the HashMap 
        if(customerCity.containsKey(customerName)) { 
        // Get the value assigned to a given key in the HashMap
          String city = customerCity.get(customerName); 
          System.out.println(customerName + " lives in " + city); 
      
          } else {
             System.out.println("City details not found for user " + customerName);
          } 
          // Check if a value exists in a HashMap
         if(customerCity.containsValue("Chennai")) {
             System.out.println("There is a user in the customerCity who lives in Chennai");
         } else {
             System.out.println("There is no user in the customerCity who lives in Chennai");
         }
         // Modify the value assigned to an existing key 
    customerCity.put(customerName, "Kolkata"); 
    System.out.println(customerName + " moved to a new city " +       customerCity.get(customerName) + ", New customerCity : " + customerCity); 
   // The get() method returns null if the specified key was not found in the HashMap
         System.out.println("Delhi city : " + customerCity.get("Delhi"));
     }
 } 

output:

is customerCity empty? : true
 customerCity HashMap : {Ganesh=Pune, Pawan=Hyderabad, Balaji=Bengaluru}
 We have the city information of 3 users
 City details not found for user Uday
 There is no user in the customerCity who lives in Chennai
 Uday moved to a new city Kolkata, New customerCity : {Ganesh=Pune, Pawan=Hyderabad, Balaji=Bengaluru, Uday=Kolkata}
 Delhi city : null

The following example shows how to :

remove(Object key):Remove a key from a HashMap  

remove(Object key, Object value):Remove a key from a HashMap only if it is associated with a given value  

 import java.util.HashMap;
  import java.util.Map;
 public class RemoveKeysHashMapExample {
      public static void main(String[] args) {
          // Creating an empty HashMap 
          Map cityZipCode = new HashMap<>();
          // Mapping int values to String keys 
          cityZipCode.put("Mumbai", 400001);
          cityZipCode.put("Kolkata",700001);
          cityZipCode.put("Hyderabad", 500001);
          cityZipCode.put("Hyderabad", 500001);
          // Displaying the HashMap 
          System.out.println("city-ZipCode  : " + cityZipCode);
          // Removing the existing key mapping 
          Integer returned_value = (Integer)cityZipCode.remove("Mumbai");
          // Checking the returned value 
          System.out.println("Returned value is: "+ returned_value);
          System.out.println(cityZipCode.put("jalna", 500001));
          // Displayin the new Hashmap
          System.out.println("city-ZipCode  : " + cityZipCode);
            boolean isRemoved=cityZipCode.remove("jalna",500001);
              System.out.println("jalna removed from the mapping?:"+isRemoved);
       // Display  new map
          System.out.println("city-ZipCode :"+cityZipCode)
}
 } 

output:

city-ZipCode  : {Kolkata=700001, Mumbai=400001, Hyderabad=500001}
 Returned value is: 400001
 null
 city-ZipCode  : {Kolkata=700001, jalna=500001, Hyderabad=500001}
 jalna removed from the mapping? : true
 city-ZipCode  : {Kolkata=700001, Hyderabad=500001}

Best ways to Iterate through HashMap in Java

As a Java programmer, everyone should know how to Iterate through HashMap, as it is part of his routine programming. Unlike other Collections, we cannot iterate through HashMap directly we need to get the keySet or entrySet to iterate.

In this article, we will learn about all the different ways of iterating a HashMap in Java.

We know that Map interface didn’t inherited from a Collection interface and thats why it will not have its own iterator. entrySet() returns a Set and a Set interface which extends the Collection interface and now on top of it, we can use the Iterator. 

we know that  we can get the key-value pair easily using the getKey() and getValue() method.

Iterate through a HashMap EntrySet using Iterator

import java.util.*;
public class ForEach {
public static void main(String args[]) {
Map customers = new HashMap<>();
customers.put(1, “Ganesh”);
customers.put(2, “Rajesh”);
customers.put(3, “Anil”);

System.out.println(“using foreach in java 8”);
Iterator<Map.Entry<Integer, String>> iterator = customers.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = iterator.next();
System.out.println(“Key : “ + entry.getKey() + ” value : “ + entry.getValue());
}

}

}

output:

Method #1: Iterating using Iterator in java 8
 Key : 1 value : Ganesh
 Key : 2 value : Rajesh
 Key : 3 value : Anil

If you using Java 8 this is the easiest way to loop the Map

import java.util.*;
public class ForEach {
public static void main(String args[]) {
Map customers = new HashMap<>();
customers.put(1, “Ganesh”);
customers.put(2, “Rajesh”);
customers.put(3, “Anil”);

System.out.println(“using foreach in java 8”);

customers.forEach((id, name) -> {
System.out.println(“Key : “ + id + ” value : “ + name);
});

}

}

output:

 Method #2: Iterating using Iterator in java 8
 Key : 1 value : Ganesh
 Key : 2 value : Rajesh
 Key : 3 value : Anil 

Different Ways to Iterate Through a Map in Java

import java.util.*;
 import java.util.stream.Stream;
 public class ForEach {
 public static void main(String args[]) {
 Map customers = new HashMap<>();
 customers.put(1, "Ganesh");
 customers.put(2, "Rajesh");
 customers.put(3, "Anil");
 System.out.println("method 1:using iterater  in java ");
 Iterator> iterator = customers.entrySet().iterator();
 while (iterator.hasNext()) {
 Map.Entry entry = iterator.next();
 System.out.println("Key : " + entry.getKey() + " value : " + entry.getValue());
 }
 System.out.println("method 2:using stream");
     customers.entrySet()
                 .stream()
                 .forEach(System.out::println);
 //Java 8 - using Iterator.forEachRemaining()
 System.out.println("method 3:Java 8 - using Iterator.forEachRemaining()");
         customers.entrySet()
                 .iterator()
                 .forEachRemaining(System.out::println);
                 // method 4 :Java 8 - using Stream.of to get Stream"
      System.out.println(" method 4 :Java 8 - using Stream.of to get Stream");
         Stream.of(customers.entrySet().toArray())
                 .forEach(System.out::println);
     System.out.println("method 5. using toString()");
     System.out.println(customers.entrySet().toString());
     System.out.println("method 6:Java 8 - using Stream.of to get Stream<String>");
     Stream.of(customers.entrySet().toString())
  //count() = 1             .forEach(System.out::println);
 }
 }

output:

method 1:using iterater  in java 
Key : 1 value : Ganesh
Key : 2 value : Rajesh
Key : 3 value : Anil
method 2:using stream
1=Ganesh
2=Rajesh
3=Anil
method 3:Java 8 - using Iterator.forEachRemaining()
1=Ganesh
2=Rajesh
3=Anil
method 4 :Java 8 - using Stream.of to get Stream
1=Ganesh
2=Rajesh
3=Anil
method 5. using toString()
[1=Ganesh, 2=Rajesh, 3=Anil]
method 6:Java 8 - using Stream.of to get Stream
[1=Ganesh, 2=Rajesh, 3=Anil]

Java HashMap with User defined objects

Check out the following example to learn how to create and work with a HashMap of user defined objects.

import java.util.HashMap;
 import java.util.Map;
 class Customer {
     private Integer id;
     private String name;
     private String city;
 public Customer(Integer id, String name, String city) {
     this.id = id; 
    this.name = name;
     this.city = city;
 }
 public Integer getId() { 
    return id;
 }
 public void setId(Integer id) { 
    this.id = id; 
}
 public String getName() { 
    return name; 
} 
public void setName(String name) {
     this.name = name;
 } public String getCity() { 
    return city; 
}
 public void setCity(String city) { 
    this.city = city;
 } 
@Override
 public String toString() {
     return "Customer{" +   
          "name='" + name + '\'' +  
           ", city='" + city + '\'' + 
            '}'; }
 }
 public class HashMapUserDefinedObjectExample {
     public static void main(String[] args) {
         Map customersMap = new HashMap<>();
     customersMap.put(1001, new Customer(1001, "Rajeev", "Bengaluru"));
customersMap.put(1002, new Customer(1002, "David", "New York"));
customersMap.put(1003, new Customer(1003, "Jams", "Paris"));System.out.println(customersMap); }
 }

output:

{1001=Customer{name='Rajeev', city='Bengaluru'}, 1002=Customer{name='David', city='New York'}, 1003=Customer{name='Jams', city='Paris'}}




Also read :

Leave a Reply