• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

Java HashMap Example

July 2, 2014 //  by Krishna Srinivasan//  Leave a Comment

HashMap is collection which stores in the form of key-value pairs, where key is reference and value is actual data. HashMap always works on the principle of hashing to transform key-value pairs into the map.

  • It uses hash table to store the map.
  • It contains unique elements.
  • We cannot use duplicate data for the keys in the HashMap.
  • For inserting and locating pairs, HashMap provides constant – time performance.
  • The performance depends on the constructor which allows adjusting capacity and loading factor of the HashMap. HashMap supports both constructor and methods.

also read:

  • Difference between ArrayList, Vector and LinkedList in Java
  • Annotations in Java 5.0 

Collection Diagram of HashMap

Java HashMap Collection Diagram Example

HashMap Features

  • HashMap is equivalent to Hashtable.
  • HashMap is non-synchronized.
  • HashMap allows null values.
  • HashMap is case-sensitive.
  • HashMap will not keep keys and values in a proper order.

HashMap Syntax

HashMap<K, V>  map = new  HashMap<K, V> ( );

Where K specifies type of keys and V specifies type of values. We can create HashMap object by using new operator as shown in the syntax.

HashMap Constructors

  • HashMap ( ): It is a default hash map.
  • HashMap (Map m): It initializes the hash map by using the elements of m.
  • HashMap (int capacity): It is used to define the initial capacity of HashMap. The default initial capacity of HashMap is 16.
  • HashMap (int capacity, float fillRatio): It initializes both capacity and fill ratio by using its arguments.

HashMap Methods

Method Description
void clear( ) Removes all the key-value pairs from the map.
Object clone( ) Returns a duplicate copy of the map.
boolean containsValue(Object value) Returns the specified value of the map.
boolean containsKey( Object key) Returns the specified key of the map.
V get( Object key) Returns the value with the specified key of the mapping.
Set<Entry> entrySet( ) Returns a set of key-value pairs contained in the map.
Set keySet ( ) Returns a set of key contained in the map.
boolean isEmpty( ) Returns true if the map contains no key or value pairs.
V put( K key, V value) Describes the specified value with the specified key in the map.
void putAll( Map map) It copies all the key-value pairs from the specified map to the required map.
int size( ) Returns the number of key and value pairs in the map.
V remove( Object key) It removes the key-value pairs from the map.
Collection values( ) Returns collection of values present in the map.

Simple Example of HashMap

package hashmap;

import java.util.*;

public class HashExample {
	public static void main(String[] args) {
	HashMap<String, String> hMap = new HashMap<String, String>();

		hMap.put("One", "Mahantesh");
		hMap.put("Two", "Maruti");

		Set set = hMap.entrySet();
		Iterator itr = set.iterator();

		while (itr.hasNext()) {
		Map.Entry m = (Map.Entry) itr.next();
		System.out.println(m.getKey() + " " + m.getValue());
		}
	}
}
  • In the above example, The HashMap interface which is used to store key values and creates HashMap object hMap by using new operator which takes parameter of type string.
  • In the next line, put the all elements to the map by using hMap.put( ) method.
  • The next line defines set of entries to the map by using entrySet( )method.
  • The iterator allows traversing of a object and the modification of the elements.
  • The itr.hasNext( ) returns true until it reaches at the end.
  • The getKey( ) and getValue( ) returns the value which the specified key is mapped in the hash map.

When you run the above example, you would get the following output:

Java Simple HashMap Example

Example using HashMap Methods


package hashmap;

import java.util.*;

public class HashMapMethodsExample {

	public static void main(String[] args) {
		HashMap<String, String> hMap = new HashMap<String, String>();

		hMap.put("One", "Mahantesh");
		hMap.put("Two", "Maruti");
		hMap.put("Three", "Ganesh");
		hMap.put("Four", "Vikrant");

		System.out.println("Before removing: "+ hMap);

		hMap.remove("Three");

		System.out.println("After removing: "+ hMap);

		boolean data=hMap.isEmpty();
		System.out.println("Is hash map empty: " + data );
		System.out.println("Size of the map: "+ hMap.size());

		System.out.println("value 'Maruti' exists: "+ hMap.containsValue("Maruti"));

        System.out.println("key 'Five' exists: "+ hMap.containsKey("Five"));

        System.out.println("Map elements: "+ hMap);

        hMap.clear();

        System.out.println("Map elements after clear: "+ hMap);

	}
}
  • In the above example we have used different HashMap Methods.
  • hMap.put( ); is used to specify value by using specified key in the map.
  • hMap.remove( ); is used to remove the elements from the map.
  • boolean isEmpty( ); is used to return true/false if the map contains any key-value pairs.
  • hMap.size( ); is used to represent the size of the map.
  • hMap.containsValue( ); is used to return true/false if the map contains any value.
  • hMap.containsKey( ); is used to return true/false if the map contains any key.
  • hMap.clear( ); is used to clear the HashMap.
  • System.out.println( ); statement is used to define the output of the used HashMap Methods.

When you run the above example, you would get the following output:

Java HashMap Methods Example

Category: JavaTag: Java Util

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Previous Post: « Java LinkedList Example
Next Post: Java HashTable Example »

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact