English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java array

Java object-oriented (I)

Java object-oriented (II)

Java object-oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java input/output (I/O)

Java Reader/Writer

Java other topics

Java HashMap values() usage and examples

Java HashMap Methods

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

The syntax of the values() method is:

hashmap.values()

values() parameters

The values() method does not take any parameters.

values() returns values

  • returns the hashmappingall valuescollection view

a collection view that displays all values of the hashmap as a collection. The view does not contain the actual values.

Note:The values() method returnsset collection view.This is because, unlike keys and entries, there may be duplicate values in a hashmap.

Example1:Java HashMap values()

import java.util.HashMap;
class Main {
  public static void main(String[] args) {
    //Create a HashMap
    HashMap<String, Integer> prices = new HashMap<>();
    //Insert entries into HashMap
    prices.put("Shoes", 200);
    prices.put("Bag", 300);
    prices.put("Pant", 150);
    System.out.println("HashMap: " + prices);
    //returns a view of all values
    System.out.println("Values: " + prices.values());
  }
}

Output Result

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

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

prices.values()

Here, the values() method returns a view of all existing values in the hash map.

The values() method can also be used withfor-each loopused together to iterate over each value in the hashmap.

Example2:for-values() method in the each loop

import java.util.HashMap;
class Main {
  public static void main(String[] args) {
    //Create 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 HashMap
    System.out.print("Values: ");
    // values() returns a view of all values
    // for-The each loop accesses each value from the view
    for (int value : numbers.values()) {}}
      //Print each value
      System.out.print(value + ", ");
    }
  }
}

Output Result

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

In the above example, we created a hash map named numbers. Note this line,

Integer value: numbers.values()

Here, the values() method returnsall valuesofView. The variable value accesses each value from the view.

NoteThe value of HashMap is of Integer type. Therefore, we use an int variable to access the value.

Recommended Reading

Java HashMap Methods