Generic map print function

generics, java

Solution

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:

- Angelika Langer - Generic Methods

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() );
    }
}

Problem

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.

Original source