Friday 27 December 2019

dictionary - How do I efficiently iterate over each entry in a Java Map?

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> maps = new ArrayList>() {
private static final long serialVersionUID = 1L;
{
add(new LinkedHashMap() {
private static final long serialVersionUID = 1L;
{
put("One", 0);
put("Two", 1);
put("Three", 3);
}
});
add(new LinkedHashMap() {
private static final long serialVersionUID = 1L;
{
put("Object", new Object());
put("Integer", new Integer(0));
put("Double", new Double(0.0));
}
});
}
};
for (Map map : maps) {
MapUtils.printMap(map);
System.out.println();
}
}
}

Output


One = 0
Two = 1
Three = 3
Object = java.lang.Object@15db9742
Integer = 0
Double = 0.0

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...