×

Traverse through HashMap in Java

In this tutorial, we will discuss traversing through HashMap in Java

Introduction:

HashMap<Key, Value> is a part of the java collection implemented from the java 1.2 version. HashMap is written as HashMap<K, V>, In which K, V is represented as the Key and Value and <,> represents the collection. HashMap class is available in Java. util package. It gives the fundamental execution of the Map interface in Java. It stores the information in (Key, Value) matches, and we can get to them by a record of another sort (for example, an Integer). One item is utilized as a key (index) to another entity (value). If we attempt to embed the copy key, it will replace the component of the comparing key.

HashMap is like HashTable; however, it is unsynchronized. It permits storing the invalid keys too, but there ought to be just a null key object, and there can be quite a few invalid qualities. This class makes no certifications concerning the request for the guide. To utilize HashMap and its techniques, we have to import Java. util.HashMap package or its superclass.

HashMap stores the data in (Key, Value) matches, and we can get to them by a file of another feature. HashMap class carries out a Map interface which permits us to store keys. It inside utilizes a quick hashing procedure.

Traversal Methods:

There are specific methods in traversal through HashMap, which can iterate over mapping in which the key-value pair is matched.

Methods:

  • Using an Iterator
  • Using for-each loop
  • Using forEach() Method

Method 1: Using an Iterator

Iterator is a connection point that is an interface found in Java.util package and is utilized to emphasize through a collection. As such, there is nothing exceptional to talk about iterators, so; We will propose techniques for the Iterator point of interaction being utilized to cross over HashMap.

hm.entrySet() -  is utilized to recover all the key-esteem matches called Map. Entries and stores inside into a set.

hm.entrySet().iterator() - returns an iterator that goes about as a cursor, takes a look at the important feature of the set, and continues until the end.

hmIterator.hasNext() - checks for the below features in the set and returns a boolean

hmIterator.next() - returns the below mentioned element (Map.Entry) from the set.

mapElement.getKey() - returns the key to the related Map.Entry

mapElement.getValue() - return the worth of the linked Map.Entry

Program:

// HashMap  Program Using Iterator
import java.util.*;
class Jtp
{
// Main method
public static void main(String s[])
{


// Hashmap of string-integer pairs
HashMap<String, Integer> hm
= new HashMap<String, Integer>();
                         // It contains names and marks
// Adding mappings to HashMap using object name.put() method
hm.put("Ramesh", 72);
hm.put("Arun", 81);
hm.put("Suresh", 48);


// Printing all the elements inserted into a HashMap
System.out.println("HashMap is "  + hm);


// Creating an iterator
Iterator hmIterator = hm.entrySet().iterator();
System.out.println("HashMap after adding 10 marks:");


// Iterating through Hashmap after adding ten marks
while (hmIterator.hasNext()) {
                             Map.Entry mapElement = (Map.Entry)hmIterator.next();
int marks = ((int)mapElement.getValue() + 10);


// Displaying marks after adding ten marks and corresponding names
System.out.println(mapElement.getKey() + " : " + marks);
}
}
}

Output:

HashMap is {Suresh=48, Arun=81, Ramesh=72}
HashMap after adding ten marks:
Suresh : 58
Arun : 91
Ramesh : 82

Method 2: Using for-each loop

In this method, we will use for-each loop function:

Program:

// HashMap program using  for-each Loop
import java.util.*;


// Main class
class Jtp 
{
 // Main method
public static void main(String s[])
{


// HashMap of string-integer pairs
HashMap<String, Integer> hm
= new HashMap<String, Integer>();
                  // It contains the name and marks of the student
// Adding mappings to HashMap using object name.put() method
hm.put("Ramesh", 72);
hm.put("Arun", 81);
hm.put("Suresh", 48);


// Displaying elements of HashMap
System.out.println("Hashmap is" + hm);


// Display message to add ten marks 
System.out.println(
"HashMap after adding 10 marks:");


// HashMap Using for-each loop
for (Map.Entry<String,Integer> mapElement : hm.entrySet())
 {
String key = mapElement.getKey();


// Adding ten marks to all the students
int value = (mapElement.getValue() + 10);


// Displaying marks after adding ten marks and corresponding names
System.out.println(key + " : " + value);
}
}
}

Output:

Hashmap is{Suresh=48, Arun=81, Ramesh=72}
HashMap after adding ten marks:
Suresh : 58
Arun : 91
Ramesh : 82

Method 3: Using forEach() Method

In this method, we will use forEach() function:

Code:

// HashMap  Program Using forEach() method
import java.util.*;
class Jtp
{
// Main method
public static void main(String s[])
{


// Hashmap of string-integer pairs
HashMap<String, Integer> hm
= new HashMap<String, Integer>();
                         // It contains names and marks
// Adding mappings to HashMap using object name.put() method
hm.put("Ramesh", 72);
hm.put("Arun", 81);
hm.put("Suresh", 48);


// Printing all the elements inserted into a HashMap
System.out.println("HashMap is "  + hm);
                     // Display message to add ten marks 
System.out.println("HashMap after adding 10 marks:");




// Looping of HashMap and adding ten marks
// using HashMap.forEach() method
hm.forEach((k, v)-> System.out.println(k + " : "+ (v + 10)));
}
}

Output:

HashMap is {Suresh=48, Arun=81, Ramesh=72}
HashMap after adding ten marks:
Suresh : 58
Arun : 91
Ramesh : 82

Related Topics

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Banking Application in Java

JDBC (Java Database Connectivity), which provides an API to connect to, execute, and fetch data from any databases, can be used to handle transactions in Java. There are several factors...

7 minutes read.

Different Ways to Take Input from User in Java

Any information provided to a system for use is known as user input. Any responsive software or application must include user input. In Java, there are 4 different ways to...

5 minutes read.

Java Console

If there is a character-based console device connected to the active Java virtual machine, it can be accessed using methods provided by the Java.io.Console class. JDK 6 adds the Console...

3 minutes read.

Java Math IEEEremainder() Method

The IEEEremainder() method of Math class calculates the remainder as prescribed by the IEEE754 standard. This method simply returns the remainder when f1 (dividend) is divided by f2 (divisor). Syntax: public static...

2 minutes read.

Convert milliseconds to date in Java

In Java, we frequently need to convert milliseconds into Dates with several formats, including dd MM yyyy and dd MM yyyy HH:mm:ss:SSS Z, among others. The Date class is one of the most...

4 minutes read.

Java Integer compare() method

The compare() method of Integer class compares the two specified int values. Syntax public static int compare(int x, int y) Parameters The parameters ‘x’ and ‘y’ represent the first and second int values to...

2 minutes read.

Program to Implement FLAMES Game in Java

Friends, Lovers, Affectionate, Marriage, Enemies, and Sibling are all represented by the acronym FLAMES, which also serves as the name of a well-known game. Although, it can be entertaining to...

4 minutes read.

How to Convert String to Integer in Java

How to convert String to int in Java You need to convert String into int if you want to perform a mathematical operation on string which contains digits. To do so,...

3 minutes read.

Narcissistic Number in Java

A Narcissistic number is made up of digits that have been added together and raised to powers equal to the number of digits in the original number. In those other...

3 minutes read.

Program to Reverse a Number in Java

In order to reverse a number, the digit in the first place must be swapped with the digit in the final position, the second digit with the second-to-last digit, and...

3 minutes read.

Java Arrays

An array is an object that stores a collection of values. An array can store two types of collection data: objects and primitives. An array is a collection of values which...

2 minutes read.

Program to find the duplicate characters in a string

Problem statement You have given with a string and your task is to find out the repeated characters from the string and print them. If no character is repeated, then you...

2 minutes read.

Java Macros

Macros are additions to the JDK 7 compiler in Java. Compile time macros are added and supported. Macros are Java classes that are instantiated and executed during the compilation process....

2 minutes read.

Difference between C, C++, java

C Language: C language is a procedure oriented language. It has been invented by Dennis Ritchie in the year 1970. It is one of the computer programming language. The purpose of...

3 minutes read.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

Methods in Java

The Methods in Java are the collection of statements that are executed when the method is called. By using the methods, the complexity of writing the code decreases. The method consists...

4 minutes read.

Replace character in string Java

Characters in Java In the package of Java language, there is a container class called Character. A single field of type char is contained in a Character object. For manipulating characters,...

4 minutes read.

Java Speech Recognition

The customer experience and convenience are improved with its utilization. Command and control interest in buying and voice synthesizers are supported by the cross-platform API defined by the API. For...

4 minutes read.