Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

hashmap

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.

like image 358
Gandolf Avatar asked Apr 21 '16 23:04

Gandolf


People also ask

How do I print a String object map?

Print HashMap Elements in Java This is the simplest way to print HashMap in Java. Just pass the reference of HashMap into the println() method, and it will print key-value pairs into the curly braces. See the example below.

Does Java map allow duplicates?

The map implementations provided by the Java JDK don't allow duplicate keys. If we try to insert an entry with a key that exists, the map will simply overwrite the previous entry.

Can you have duplicate values in a map?

Map does not supports duplicate keys. you can use collection as value against same key. Because if the map previously contained a mapping for the key, the old value is replaced by the specified value.


2 Answers

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)); 
like image 144
BeUndead Avatar answered Oct 09 '22 08:10

BeUndead


You may use Map.entrySet() method:

for (Map.Entry entry : objectSet.entrySet()) {     System.out.println("key: " + entry.getKey() + "; value: " + entry.getValue()); } 
like image 42
Andrej Istomin Avatar answered Oct 09 '22 07:10

Andrej Istomin