java 任何可以快速打印地图的实用程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5631291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 12:00:31  来源:igfitidea点击:

Any utility which can print out map quickly

java

提问by user496949

I am wondering any utility to print out map quickly for debugging purpose.

我想知道任何用于快速打印地图以进行调试的实用程序。

回答by ColinD

You can just print the toString()of a Mapto get a 1-line version of the map, divided up in to key/value entries. If that isn't readable enough, you could do your own looping to print or use Guavato do this:

你可以只打印toString()Map拿到地图,在划分为键/值项的1行版本。如果这不够可读,您可以自己循环打印或使用Guava来执行此操作:

System.out.println(Joiner.on('\n').withKeyValueSeparator(" -> ").join(map));

That'll give you output of the form

那会给你表格的输出

key1 -> value1
key2 -> value2
...

回答by weekens

I guess, the .toString() method of implementing class (HashMap or TreeMap for ex.) will do what you want.

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

回答by hs11373

Consider: MapUtils (Commons Collection 4.2 API)

考虑:MapUtils(Commons Collection 4.2 API)

It has two methods: debugPrint & verbosePrint.

它有两种方法:debugPrint 和verbosePrint。

回答by Ramkumar Pillai

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

回答by Harry Joy

How about this:

这个怎么样:

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));
}

or simply:

或者干脆:

System.out.println(map.toString());

回答by StKiller

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);
    }
}

Output:

输出:

{key2=value2, key1=value1}

回答by janhink

I think that System.out.printlnworks very well with a map, as this:

我认为这System.out.println对地图非常有效,因为:

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("key1", 1);
map.put("key2", 2);        
System.out.println(map);

prints:

印刷:

{key1=1, key2=2}

Or you can define an utility method like this:

或者你可以像这样定义一个实用方法:

public void printMap(Map<?, ?> map)
{
    for (Entry<?, ?> e : map.entrySet())
    {
        System.out.println("Key: " + e.getKey() + ", Value: " + e.getValue());
    }
}

回答by KapudanPasha

Try using StringUtils.join(from Commons Lang)

尝试使用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(), "|"));

will produce

会产生

abc=123|xyz=456