快速打印地图的任何实用工具

8
我想知道是否有任何工具可以快速打印地图以进行调试。

1
你可以使用迭代器和for循环在两行中打印出成员。 - user684934
公共类测试 { public static void main(String [] args) throws Exception { java.util.Map<Object, Object> m = new java.util.HashMap<Object, Object>(); m.put(1, 2); m.put(3, 4); System.err.println(""+m); } } - khachik
8个回答

13
你可以直接打印MaptoString()方法来得到一个一行的版本,其中包含了键/值对。如果这个输出不够可读,你可以自己编写循环来打印或使用Guava库来实现:
System.out.println(Joiner.on('\n').withKeyValueSeparator(" -> ").join(map));

这将会给你一个以下形式输出:

键1 -> 值1
键2 -> 值2
...

8
我猜,实现类的.toString()方法(例如HashMap或TreeMap)会做你想要的事情。

HashMap.toString的示例输出:{key1=value1,key2=value2}。这对于调试目的已经足够好了。 - Nicolas Raoul

5
  org.apache.commons.collections.MapUtils.debugPrint(System.out, "Print this", myMap);

5

3
这样怎么样:
Map<String, String> map = new HashMap<String, String>();
for (Iterator<String> iterator = map.keySet().iterator(); iterator.hasNext();) {
    String key = (String) iterator.next();
    System.out.println(map.get(key));
}

或者简单地说:
System.out.println(map.toString());

3
public final class Foo {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        System.out.println(map);
    }
}

输出:

{key2=value2, key1=value1}

2
我认为System.out.println与map结合使用效果非常好,如下所示:
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("key1", 1);
map.put("key2", 2);        
System.out.println(map);

打印:

{key1=1, key2=2}

或者您可以定义一个类似这样的实用方法:
public void printMap(Map<?, ?> map)
{
    for (Entry<?, ?> e : map.entrySet())
    {
        System.out.println("Key: " + e.getKey() + ", Value: " + e.getValue());
    }
}

2
尝试使用 StringUtils.join(来自Commons Lang)。
例如:
Map<String, String> map = new HashMap<String, String>();
map.put("abc", "123");
map.put("xyz", "456");

System.out.println(StringUtils.join(map.entrySet().iterator(), "|"));

将产生
abc=123|xyz=456

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接