In this guide, you will learn about the Map values() method in Java programming and how to use it with an example.
1. Map values() Method Overview
Definition:
The values() method of the Java Map interface returns a collection view of the values present in the map.
Syntax:
Collection<V> valuesCollection = map.values();
Parameters:
- This method does not take any parameters.
Key Points:
- The method returns a Collection containing all the values from the map.
- The collection is backed by the map, meaning changes to the map are reflected in the collection, and vice-versa.
- Removing an item from the returned collection will remove the corresponding key-value pair from the map.
- Unlike the key set, the collection of values might contain duplicates if the map has multiple keys mapped to the same value.
- The collection supports element removal, which also removes the corresponding key-value pair from the map, but it does not support the add or addAll operations.
2. Map values() Method Example
import java.util.HashMap;
import java.util.Map;
import java.util.Collection;
public class MapValuesExample {
public static void main(String[] args) {
Map<String, String> countryCapital = new HashMap<>();
// Populate the map
countryCapital.put("USA", "Washington, D.C.");
countryCapital.put("UK", "London");
countryCapital.put("India", "New Delhi");
// Retrieve the values
Collection<String> capitals = countryCapital.values();
// Print the values
System.out.println("Capitals: " + capitals);
}
}
Output:
Capitals: [Washington, D.C., London, New Delhi]
Explanation:
In the provided example:
1. We instantiated a HashMap and filled it with countries as keys and their respective capitals as values.
2. We then utilized the values() method to fetch a collection view of the capitals.
3. Finally, we printed the collection of capitals.
The values() method offers a straightforward mechanism to obtain a collection of map values, which is especially handy when one needs to process or modify all the values in a map.
Related Map Interface methods
Java Map put() example
Java Map get() example
Java Map remove() example
Java Map containsKey() example
Java Map containsValue() example
Java Map keySet() example
Java Map values() example
Java Map entrySet() example
Comments
Post a Comment
Leave Comment