YouTip LogoYouTip

Java Hashmap Entryset

# Java HashMap entrySet() Method [![Image 3: Java HashMap](#) Java HashMap](#) The entrySet() method returns a Set view of the mappings contained in the map. The syntax for the entrySet() method is: hashmap.entrySet() **Note:** hashmap is an object of the HashMap class. **Parameter Explanation:** * None ### Return Value Returns a Set view of the mappings contained in this map. **Note:** The Set view means that all key-value pairs in the HashMap are treated as a set collection. ### Example The following example demonstrates the use of the entrySet() method: ## Example import java.util.HashMap; class Main { public static void main(String[] args){ // Create a HashMap HashMap sites =new HashMap(); // Add some elements to the HashMap sites.put(1, "Google"); sites.put(2, ""); sites.put(3, "Taobao"); System.out.println("sites HashMap: "+ sites); // Return the set view of the mapping relationships System.out.println("Set View: "+ sites.entrySet()); } } The output of the above program is: sites HashMap: {1=Google, 2=, 3=Taobao}Set View: [1=Google, 2=, 3=Taobao] The entrySet() method can be used with a for-each loop to iterate through each mapping entry in the HashMap. ## Example import java.util.HashMap; import java.util.Map.Entry; class Main { public static void main(String[] args){ // Create a HashMap HashMap numbers =new HashMap(); numbers.put("One", 1); numbers.put("Two", 2); numbers.put("Three", 3); System.out.println("HashMap: "+ numbers); // Access each mapping entry in the HashMap System.out.print("Entries: "); // entrySet() returns a set view of all mapping entries in the HashMap // The for-each loop accesses each entry in this view for(Entry entry: numbers.entrySet()){ System.out.print(entry); System.out.print(", "); } } } The output of the above program is: HashMap: {One=1, Two=2, Three=3}Entries: One=1, Two=2, Three=3, [![Image 4: Java HashMap](#) Java HashMap](#)
← Java Hashmap ValuesJava Hashmap Getordefault β†’