Here is a generic type-safe method which can be called to dump any given Map
.
import java.util.Iterator;
import java.util.Map;
public class MapUtils {
static interface ItemCallback {
void handler(K key, V value, Map map);
}
public static void forEach(Map map, ItemCallback callback) {
Iterator> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = it.next();
callback.handler(entry.getKey(), entry.getValue(), map);
}
}
public static void printMap(Map map) {
forEach(map, new ItemCallback() {
@Override
public void handler(K key, V value, Map map) {
System.out.println(key + " = " + value);
}
});
}
}
Example
Here is an example of its use. Notice that the type of the Map
is inferred by the method.
import java.util.*;
public class MapPrinter {
public static void main(String[] args) {
List
Output
One = 0
Two = 1
Three = 3
Object = java.lang.Object@15db9742
Integer = 0
Double = 0.0
No comments:
Post a Comment