YouTip LogoYouTip

Java Hashmap Values

# Java HashMap values() Method [![Image 3: Java HashMap](#) Java HashMap](#) The values() method returns a Set view of all the values contained in the mapping. The syntax for the values() method is: hashmap.values() **Note:** hashmap is an object of the HashMap class. **Parameter Description:** * None ### Return Value Returns a collection view of all the value values in the HashMap. ### Example The following example demonstrates the use of the values() 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 a view of all value values System.out.println("Values: "+ sites.values()); } } The output of the above program is: sites HashMap: {1=Google, 2=, 3=Taobao}Values: [Google, , Taobao] The values() method can be used with a for-each loop to iterate over all the values in the HashMap. ## 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); // Access all values in the HashMap System.out.print("Values: "); // values() returns a view of all values // The for-each loop can access each value from the view for(String value: sites.values()){ // Output each value System.out.print(value +", "); } } } The output of the above program is: sites HashMap: {1=Google, 2=, 3=Taobao}Values: Google, , Taobao, [![Image 4: Java HashMap](#) Java HashMap](#)
← Python3 Os FdopenJava Hashmap Entryset β†’