我想知道为了调试目的而快速打印出地图的任何工具。
答案 0 :(得分:11)
您只需打印toString()
的{{1}}即可获得地图的1行版本,并将其划分为键/值条目。如果这不够可读,您可以自己进行循环打印或使用Guava来执行此操作:
Map
那将为您提供表格
的输出key1 -> value1 key2 -> value2 ...
答案 1 :(得分:8)
我想,实现类的.toString()方法(例如HashMap或TreeMap)会做你想要的。
答案 2 :(得分:6)
考虑:MapUtils (Commons Collection 4.2 API)
它有两种方法:debugPrint& verbosePrint。
答案 3 :(得分:4)
org.apache.commons.collections.MapUtils.debugPrint(System.out, "Print this", myMap);
答案 4 :(得分: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());
答案 5 :(得分: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}
答案 6 :(得分:2)
我认为System.out.println
与地图的效果非常好,因为:
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());
}
}
答案 7 :(得分:2)
尝试使用StringUtils.join
(来自Commons Lang)
e.g。
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