Java generic method: Print key-value pairs in a map
Java Generic: Exercise-7 with Solution
Write a Java program to create a generic method that takes a map of any type and prints each key-value pair.
Sample Solution:
Java Code:
// Print_map_elements.java
// Print_map_elements Class
import java.util.HashMap;
import java.util.Map;
public class Print_map_elements {
public static > K, V > void printMap(Map > K, V > map) {
for (Map.Entry > K, V > entry: map.entrySet()) {
K key = entry.getKey();
V value = entry.getValue();
System.out.println("Key: " + key + ", Value: " + value);
}
}
public static void main(String[] args) {
Map > String, Integer > colorMap = new HashMap > > ();
colorMap.put("Red", 1);
colorMap.put("Green", 2);
colorMap.put("Blue", 3);
System.out.println("Color Map:");
printMap(colorMap);
Map > String, String > capitalMap = new HashMap > > ();
capitalMap.put("Germany ", "Berlin");
capitalMap.put("USA", "Washington, D.C.");
capitalMap.put("UK", "London");
capitalMap.put("France", "Paris");
System.out.println("\nCapital Map:");
printMap(capitalMap);
}
}
Sample Output:
Color Map: Key: Red, Value: 1 Key: Blue, Value: 3 Key: Green, Value: 2 Capital Map: Key: Germany , Value: Berlin Key: USA, Value: Washington, D.C. Key: UK, Value: London Key: France, Value: Paris
Explanation:
In the above exercise, we define a generic method printMap() that takes a map "map" as input. The method iterates over the map's key-value pairs using a for-each loop and Map.Entry. For each entry, it retrieves the key and value using the getKey() and getValue() methods respectively. It then prints the key-value pair using System.out.println().
In the main() method, we demonstrate the printMap() method by passing a ColorMap containing mappings of number names to their values. We also pass a capitalMap containing mappings of country names to their capitals. We call the printMap() method for each map to print their respective key-value pairs.
Flowchart:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Filter list with predicate.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-exercises/generic/java-generic-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics