Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic map print function

Tags:

java

generics

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.

like image 355
Sait Avatar asked Nov 01 '25 10:11

Sait


2 Answers

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() );
    }
}
like image 199
Rohit Jain Avatar answered Nov 03 '25 23:11

Rohit Jain


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.

like image 30
Prasad Kharkar Avatar answered Nov 04 '25 00:11

Prasad Kharkar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!