I have a function prints Map objects,
public static void printMap(Map<Integer, Integer> map) {
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println( entry.getKey() + " " + entry.getValue() );
}
}
Now, I want my function to work with Map<String, Integer> type of maps too. How to do it? I always wanted to use generics, hope to have a good start with this question.
You can write generic methods as in below code:
public static <K, V> void printMap(Map<K, V> map) {
for (Map.Entry<K, V> entry : map.entrySet()) {
System.out.println( entry.getKey() + " " + entry.getValue() );
}
}
Suggested Read:
As pointed out by @JBNizet in comments, you can also write the method using wildcards (?) instead of type parameters as below:
public static void printMap(Map<?, ?> map) {
for (Map.Entry<?, ?> entry : map.entrySet()) {
System.out.println( entry.getKey() + " " + entry.getValue() );
}
}
You can do this with wildcard Map<? extends Object, Integer>. This line means that you can have anything that extends Object class. So it can be String, Integer, UserDefinedObject. Anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With