Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing HashMap In Java

People also ask

How do I print a HashMap in Java?

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.

Can you print a map Java?

Using toString() For displaying all keys or values present on the map, we can simply print the string representation of keySet() and values() , respectively. That's all about printing out all keys and values from a Map in Java.

How do you print a HashMap for each loop?

Example: Java HashMap forEach() forEach((key, value) -> { value = value - value * 10/100; System. out. print(key + "=" + value + " "); });


keySet() only returns a set of keys from your hash map, you should iterate this key set and the get the value from the hash map using these keys.

In your example, the type of the hash map's key is TypeKey, but you specified TypeValue in your generic for-loop, so it cannot be compiled. You should change it to:

for (TypeKey name: example.keySet()) {
    String key = name.toString();
    String value = example.get(name).toString();
    System.out.println(key + " " + value);
}

Update for Java8:

example.entrySet().forEach(entry -> {
    System.out.println(entry.getKey() + " " + entry.getValue());
});

If you don't require to print key value and just need the hash map value, you can use others' suggestions.

Another question: Is this collection is zero base? I mean if it has 1 key and value will it size be 0 or 1?

The collection returned from keySet() is a Set. You cannot get the value from a set using an index, so it is not a question of whether it is zero-based or one-based. If your hash map has one key, the keySet() returned will have one entry inside, and its size will be 1.


A simple way to see the key value pairs:

Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
System.out.println(Arrays.asList(map)); // method 1
System.out.println(Collections.singletonList(map)); // method 2

Both method 1 and method 2 output this:

[{b=2, a=1}]

Assuming you have a Map<KeyType, ValueType>, you can print it like this:

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

To print both key and value, use the following:

for (Object objectName : example.keySet()) {
   System.out.println(objectName);
   System.out.println(example.get(objectName));
 }

You have several options

  • Get map.values() , which gets the values, not the keys
  • Get the map.entrySet() which has both
  • Get the keySet() and for each key call map.get(key)

For me this simple one line worked well:

Arrays.toString(map.entrySet().toArray())