Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

hashtable
entryset
java
communitycreator

What is the Hashtable.entrySet method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

A hash table is a collection of key-value pairs.

In Java, the Hashtableclass includes the entrySet method, which gets all the entrieskey-value mappings of the Hashtable object as a Set view.

Any changes made to the hash table will be reflected in the Set view as well.

Syntax

public Set<Map.Entry<K,V>> entrySet()

Parameters

This method doesn’t take any parameters.

Return value

The entrySet method returns a Set view of all of the entries on the Hashtable object.

Code

The example below shows how to use the entrySet method.

import java.util.Hashtable;
import java.util.Set;
import java.util.Map;

class EntrySetExample {
    public static void main( String args[] ) {
        Hashtable<Integer, String> map = new Hashtable<>();
        map.put(1, "one");
        map.put(2, "two");
        
        System.out.println("The map is -" + map );

        Set<Map.Entry<Integer, String>> entries = map.entrySet();
        System.out.println("The entries are -" +   entries);

        System.out.println("\nAdding a new entry 4 - four to the map" );
        map.put(4, "four");

        System.out.println("After adding the entries are -" + entries);
    }
}

Explanation

In the code above:

  • In line 1, we import the Hashtable class.

  • In line 7, we create a Hashtable object with the name map.

  • In lines 8 and 9, we use the put method to add two mappings ({1=one, 2=two}) to the map object.

  • In line 13, we get the map object entries with the entrySet method and store them in the entries variable.

  • In line 17, we add a new entry 4 - "four" to the map.

  • In line 19, we print the entries object. The newly added entry, 4 - "four" will be automatically available in the entries variable without the need to call the entrySet method because the entrySet method returns the set view.

RELATED TAGS

hashtable
entryset
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring