English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)/O)

Java Reader/Writer

Java Other Topics

Java HashMap entrySet() Usage and Example

Java HashMap Methods

The Java HashMap entrySet() returns a collection view of all the mappings (entries) present in the hash map.

The syntax of the entrySet() method is:

hashmap.entrySet()

entrySet() parameter

The entrySet() method does not take any parameters.

entrySet() return value

  • Returns a set view of all entries in the hashmap

Note: set view means that all entries in the hashmap are considered as a collection. Entries are not converted to a collection.

Example1: Java HashMap entrySet()

import java.util.HashMap;
class Main {
  public static void main(String[] args) {
    // Create a HashMap
    HashMap<String, Integer> prices = new HashMap<>();
    // Insert entries into HashMap
    prices.put("Shoes", 200);
    prices.put("Bag", 300);
    prices.put("Pant", 150);
    System.out.println("HashMap: "); + prices);
    //Returns a set view of the map
    System.out.println("Set view: "); + prices.entrySet());
  }
}

Output Result

HashMap: {Pant=150, Bag=300, Shoes=200}
Set view: [Pant=150, Bag=300, Shoes=200]

In the above example, we created a hash map named prices. Note the expression

prices.entrySet()

Here, the entrySet() method returns a view of the set of all entries from the hash map.

the entrySet() method can be used withfor-each loopused together to iterate over each entry in the hash map.

Example2: for-entrySet() method in each loop

import java.util.HashMap;
import java.util.Map.Entry;
class Main {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap<String, Integer> numbers = new HashMap<>();
        numbers.put("One", 1);
        numbers.put("Two", 2);
        numbers.put("Three", 3);
        System.out.println("HashMap: "); + numbers);
        //Access each entry in the hashmap
        System.out.print("Entries: ");
        //entrySet() returns a view of the set of all entries
        //for-each loop visits each entry in the view
        for(Entry<String, Integer> entry: numbers.entrySet()) {
            System.out.print(entry);
            System.out.print(", ");
        }
    }
}

Output Result

HashMap: {One=1, Two=2, Three=3}
Entries: One=1, Two=2, Three=3,

In the above example, we imported the java.util.Map.Entry package. Map.Entry is a nested class of the Map interface. Note this line,

Entry<String, Integer> entry : numbers.entrySet()

Here, the entrySet() method returns a view of the collection of all entries. The Entry class allows us to store and print each entry in the view.

Related Reading

Java HashMap Methods