How about Printing Java maps?

See English answers > How do I effectively iterate over each entry in a Java map? 38

I created the following maps:

Map<String,Object> objectSet = new HashMap<>();

The object has its own class and its own instance variables

I have filled the map above with data

I created a printmap method, but it seems that I can only print the keys of the map

How do I make the map print < Object > the value of a for each cycle?

So far, I have:

for (String keys : objectSet.keySet())
{
   System.out.println(keys);
}

Print out key above I want to be able to print out object variables

Solution

I'm sure there are some good libraries that can do this for you... But as long as you stick to the methods you've used, map#entryset will give you a composite object with keys and values So it's similar to:

for (Map.Entry<String,Object> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ":" + entry.getValue().toString());
}

Will do what you want to do

If you are using java 8, there are new streaming methods

map.forEach((key,value) -> System.out.println(key + ":" + value));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>