Join our newsletter for the latest updates.

Java HashMap values()

The Java HashMap values() method returns a view of all the values present in entries of the hashmap.

The syntax of the values() method is:

hashmap.values()

Here, hashmap is an object of the HashMap class.


values() Parameters

The values() method does not take any parameter.


values() Return Value

  • returns a collection view of all values of the hashmap

The collection view only shows all values of the hashmap as one of the collection. The view does not contain actual values. To learn more about the view in Java, visit the view of a collection.

Note: The values() method returns the collection view. It is because unlike keys and entries, there can be duplicate values in hashmap.


Example 1: Java HashMap values()

import java.util.HashMap;

class Main {
  public static void main(String[] args) {
    // create an HashMap
    HashMap<String, Integer> prices = new HashMap<>();

    // insert entries to the HashMap
    prices.put("Shoes", 200);
    prices.put("Bag", 300);
    prices.put("Pant", 150);
    System.out.println("HashMap: " + prices);

    // return view of all values
    System.out.println("Values: " + prices.values());
  }
}

Output

HashMap: {Pant=150, Bag=300, Shoes=200}
Values: [150, 300, 200]

In the above example, we have created a hashmap named prices. Notice the expression,

prices.values()

Here, the values() method returns a view of all the values present in the hashmap.

The values() method can also be used with the for-each loop to iterate through each value of the hashmap.


Example 2: values() Method in for-each Loop

import java.util.HashMap;

class Main {
  public static void main(String[] args) {

    // Creating 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 all values  of the HashMap
    System.out.print("Values: ");

    // values() returns a view of all values
    // for-each loop access each value from the view
    for(int value: numbers.values()) {

      // print each value
      System.out.print(value + ", ");
    }
  }
}

Output

HashMap: {One=1, Two=2, Three=3}
Values: 1, 2, 3, 

In the above example, we have created a hashmap named numbers. Notice the line,

Integer value:  numbers.values()

Here, the values() method returns a view of all values. The variable value access each value from the view.

Note: The Value of HashMap is of Integer type. Hence, we have used the int variable to access the values.


Recommended Reading