1. Introduction
The HashMap class in Java, part of the java.util package, stores key-value pairs. To obtain a collection view of the values present in the map, we can use the values() method of the HashMap class. This method returns a Collection of values contained in the map. This blog post demonstrates how to use the values() method to retrieve and display the values stored in a HashMap.
2. Program Steps
1. Create a HashMap and add some key-value pairs.
2. Call the values() method on the HashMap object to retrieve the values.
3. Iterate over the collection of values and print each value to the console.
3. Code Program
import java.util.HashMap;
import java.util.Map;
import java.util.Collection;
public class HashMapValues {
public static void main(String[] args) {
// Step 1: Create a HashMap and add some key-value pairs
Map<String, Integer> map = new HashMap<>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
// Step 2: Call the values() method to retrieve the values from the HashMap
Collection<Integer> values = map.values();
// Step 3: Iterate over the collection of values and print each one
System.out.println("Values in the HashMap:");
for(Integer value : values) {
System.out.println(value);
}
}
}
Output:
Values in the HashMap: 1 2 3
4. Step By Step Explanation
Step 1: We create a HashMap named map and populate it with three key-value pairs, where the keys are strings representing numbers and the values are integers.
Step 2: The values() method is called on the map object, which returns a Collection containing all the values present in the map. This collection is stored in the values variable.
Step 3: We use an enhanced for loop to iterate over the collection of values and print each value to the console. The order of values in the output may not be in any specific order, as HashMap does not maintain any order for its elements.