English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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()
The entrySet() method does not take any parameters.
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.
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.
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
HashMap keySet() - Return a view of the set of all keys
HashMap values() - Return a view of the collection of all values