Printing a java map Map<String, Object> - How?

200,949

Solution 1

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 and the value. So something like:

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.

map.forEach((key, value) -> System.out.println(key + ":" + value));

Solution 2

You may use Map.entrySet() method:

for (Map.Entry entry : objectSet.entrySet())
{
    System.out.println("key: " + entry.getKey() + "; value: " + entry.getValue());
}

Solution 3

There is a get method in HashMap:

for (String keys : objectSet.keySet())  
{
   System.out.println(keys + ":"+ objectSet.get(keys));
}
Share:
200,949

Related videos on Youtube

Gandolf
Author by

Gandolf

Updated on August 01, 2022

Comments

  • Gandolf
    Gandolf almost 2 years

    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

    How to do I get the map to print the <Object> values using a for each loop?

    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.

    • Savior
      Savior about 8 years
      Does Map only have a keySet method? Does it have no other methods?
    • chrylis -cautiouslyoptimistic-
      chrylis -cautiouslyoptimistic- about 8 years
      Did you just try println(map)?
  • Quazi Irfan
    Quazi Irfan over 6 years
    I'd be careful when using this approach for time-sensitive applications because internally get method is linearly searching O(n) for the corresponding value.
  • randominstanceOfLivingThing
    randominstanceOfLivingThing over 6 years
    The get method internally makes a call to getNode(hash(key), key) which uses hashing. It does a linear search only when there is a hash collision.
  • as - if
    as - if almost 6 years
    linked the lambda function from J8
  • James Drinkard
    James Drinkard almost 6 years
    This answer should have been accepted. Poor SO etiquette! Thanks for posting.