×

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

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.

Java Math floorDiv() Method

The floorDiv () method of Math class returns the largest integer value that is less than or equal to the algebraic quotient. It firstly divides the dividend and divisor and...

2 minutes read.

Java Pop

The array, linked list, stack, queue, and other data structures are supported by Java programming. The insertion, deletion, and element searching operations are available for every data structure. And Java...

4 minutes read.

Hashtable in Java

Hashtable in Java The Hashtable class implements the Map interface and extends the Dictionary class. It implements a hash table which shows the key-value relation, i.e., it maps the keys to the values....

9 minutes read.

How to check Date Null in Java?

In this section, we will be acknowledged about Date Null in Java. The date null in Java is an entity that is used when there is no specified value for...

3 minutes read.

Transient variable in Java

In this article, you will be acknowledged about transient variable along with its functions. We would conclude by understanding an example program about it. Transient variable By introducing the transitory keyword, we...

3 minutes read.

Java Imageio

The javax.imageio package contains the final class known as Java ImageIO. For easy image reading, writing, and simple encoding and decoding, the class offers a convenient way. The class offers...

4 minutes read.

How to Convert Binary to Decimal in Java

How to Convert Binary to Decimal in Java There are two methods to convert binary to decimal. Using Integer.parseInt() method Using user-defined logic Using Integer.parseInt() method The parseInt() is a static method of...

2 minutes read.

Switch Case with Enum in Java

From some conditions, the java switch statement executes one statement. Similar to the If-Else-If ladder statement, this can be Byte, short, int, long, enum, string, and some wrapper types like...

4 minutes read.

Local Minima in Java

An Array Finding a local minimum in an array a[0. m-1] of different integers is the job. A[i] is considered a local minimum if it is smaller than two of its...

4 minutes read.

How to Convert Decimal to Hexadecimal in Java

How to Convert Decimal to Hexadecimal in Java The hexadecimal number uses 16 values to represent a number. Numbers from 0 to 9 represented by digits and the numbers from 10...

3 minutes read.

Java Array Generic

Creating Generic Array in Java A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's...

4 minutes read.

Generics in Java

Generics in Java Parameterizedtypes mean generic. Generics allow types (Character, Integer, String, …, etc., as well as user-defined types) to act as parameters to interfaces, classes, and methods. Generics in Java...

9 minutes read.

String Array in Java

String Array in Java An array is alinear data structure that stores similar type of data. It allows us to store fixed number of elements.It can be of different data types...

6 minutes read.

Java Class Methods

Methods called on a class rather than a specific object instance are known as class methods. The static modifier guarantees uniform implementation across all instances of the class. Syntax public class NameOfClass...

3 minutes read.

How to Create an Object in Java

How to Create an Object in Java An object can be defined as a run time entity that contains the blue printof the class. It means that all the member functions...

5 minutes read.

What’s new in Java 12

On March 19th, 2019, the Java 12th edition was released. After releasing this edition, they have decided to release every new edition every six months. This version is the advanced...

5 minutes read.

What are Array strings in Java?

In normal programming, An array is a group and a collection of identical forms of data that are stored in a sequential memory region and may be accessed using their...

4 minutes read.

Best Java Libraries

One of the most widely used programming languages is Java. Java has a large number of libraries, including the standard Java library that includes libraries such as java.lang, java.util, and...

7 minutes read.

Class memory in Java

Anything specifically defined in the Java code is stored either inside the heap or the stack, which is particularly significant. Stack and heap are the two kinds of memory available...

6 minutes read.