Easy Tutorial
❮ Java String Equals Java Arraylist Containsall ❯

Java HashMap values() Method

Java HashMap

The values() method returns a Set view of all the values contained in the map.

The syntax for the values() method is:

hashmap.values()

Note: hashmap is an object of the HashMap class.

Parameter:

Return Value

Returns a collection view of all the values contained 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&lt;Integer, String> sites = new HashMap<>();

        // Add some elements to the HashMap
        sites.put(1, "Google");
        sites.put(2, "tutorialpro");
        sites.put(3, "Taobao");
        System.out.println("sites HashMap: " + sites);

        // Return a view of all values
        System.out.println("Values: " + sites.values());
    }
}

Output:

sites HashMap: {1=Google, 2=tutorialpro, 3=Taobao}
Values: [Google, tutorialpro, Taobao]

The values() method can be used with a for-each loop to iterate through all the values in the HashMap.

Example

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap&lt;Integer, String> sites = new HashMap<>();

        // Add some elements to the HashMap
        sites.put(1, "Google");
        sites.put(2, "tutorialpro");
        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
        // for-each loop can access each value from the view
        for(String value: sites.values()) {
            // Print each value
            System.out.print(value + ", ");
        }
    }
}

Output:

sites HashMap: {1=Google, 2=tutorialpro, 3=Taobao}
Values: Google, tutorialpro, Taobao,

Java HashMap

❮ Java String Equals Java Arraylist Containsall ❯