打印 java 地图 Map<String, Object> - 如何?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36782231/
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
Printing a java map Map<String, Object> - How?
提问by Gandolf
How to I print information from a map that has the object as the value?
如何从以对象为值的地图打印信息?
I have created the following map:
我创建了以下地图:
Map<String, Object> objectSet = new HashMap<>();
The object has its own class with its own instance variables
对象有自己的类和自己的实例变量
I have already populated the above map with data.
我已经用数据填充了上面的地图。
I have created a printMap
method, but I can only seem to print the Keys of the map
我创建了一个printMap
方法,但我似乎只能打印地图的键
How to do I get the map to print the <Object>
values using a for each loop?
如何获取地图以<Object>
使用 for 每个循环打印值?
So far, I've got:
到目前为止,我有:
for (String keys : objectSet.keySet())
{
System.out.println(keys);
}
The above prints out the keys. I want to be able to print out the object variables too.
以上打印出密钥。我也希望能够打印出对象变量。
回答by Andrej Istomin
You may use Map.entrySet()
method:
您可以使用Map.entrySet()
方法:
for (Map.Entry entry : objectSet.entrySet())
{
System.out.println("key: " + entry.getKey() + "; value: " + entry.getValue());
}
回答by randominstanceOfLivingThing
回答by BeUndead
I'm sure there's some nice library that does this sort of thing already for you... But to just stick with the approach you're already going with, Map#entrySet
gives you a combined Object
with the key
andthe value
. So something like:
我敢肯定有,做这样的事情已经给你一些不错的图书馆......但只是坚持使用你已经有去的办法,Map#entrySet
给你一个联合Object
与key
和的value
。所以像:
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue().toString());
}
will do what you're after.
会做你想要的。
If you're using java 8, there's also the new streaming approach.
如果您使用的是 java 8,还有新的流方法。
map.forEach((key, value) -> System.out.println(key + ":" + value));