Java HashMap values() Method

Java HashMap Java HashMap

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

The syntax of 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 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<Integer, String> sites = new HashMap<>();

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

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

    }
}

The output of the above program is:

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

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

Example

import java.util.HashMap;

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

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

        // Access all the 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=Example, 3=Taobao}
Values: Google, Example, Taobao, 

Java HashMap Java HashMap

Other Extensions