Print HashMap in Java

I have a HashMap :

 private HashMap<TypeKey, TypeValue> example = new HashMap<TypeKey, TypeValue>(); 

Now I would like to view all the values โ€‹โ€‹and print them.

I wrote this:

 for (TypeValue name : this.example.keySet()) { System.out.println(name); } 

This does not seem to work.

What is the problem?

EDIT: Another question: is this collection based on zero? I mean, if it has 1 key and the value will be size 0 or 1?

+88
java collections
May 7 '11 at 9:09 am
source share
15 answers

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

In your example, the hashmap key type is TypeKey , but you specified TypeValue in a common for loop, so it cannot be compiled. You should change this 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 do not need to print the key value and you just need the hashmap value, you can take advantage of the suggestions of others.

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

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

+95
May 7 '11 at 9:13 AM
source share

A simple way to see 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 methods 1 and method 2 output this:

 [{b=2, a=1}] 
+72
Nov 03 '15 at 3:55
source share

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()); } 
+36
Jun 12 '13 at 14:34
source share

You have several options.

+13
May 7 '11 at 9:11 a.m.
source share

To print the key and value, use the following:

 for (Object objectName : example.keySet()) { System.out.println(objectName); System.out.println(example.get(objectName)); } 
+13
Oct 20 '14 at 4:00
source share

You want to set a value, not a set of keys:

 for (TypeValue name: this.example.values()) { System.out.println(name); } 

The code you give doesn't even compile, which may be worth mentioning in future questions - โ€œit doesn't seem to workโ€ is a bit vague!

+9
May 7 '11 at 9:12
source share

It is worth mentioning the Java 8 approach using BiConsumer and lambda functions:

 BiConsumer<TypeKey, TypeValue> consumer = (o1, o2) -> System.out.println(o1 + ", " + o2); example.forEach(consumer); 

Suppose you override the toString method for two types, if necessary.

+7
Feb 20 '15 at 12:33
source share

I did this with a String map (if you are working with a string map).

 for (Object obj : dados.entrySet()) { Map.Entry<String, String> entry = (Map.Entry) obj; System.out.print("Key: " + entry.getKey()); System.out.println(", Value: " + entry.getValue()); } 
+4
Jan 21 '15 at 13:42
source share

Java 8 new forEach style feature

 import java.util.HashMap; public class PrintMap { public static void main(String[] args) { HashMap<String, Integer> example = new HashMap<>(); example.put("a", 1); example.put("b", 2); example.put("c", 3); example.put("d", 5); example.forEach((key, value) -> System.out.println(key + " : " + value)); // Output: // a : 1 // b : 2 // c : 3 // d : 5 } } 
+3
Aug 29 '16 at 8:26
source share

A simple print statement with a variable name that contains a hash map link will do:

 HashMap<K,V> HM = new HashMap<>(); //empty System.out.println(HM); //prints key value pairs enclosed in {} 

This works because the toString() method is already overloaded in the AbstractMap class , which extends the HashMap Class Further information from the documentation.

Returns a string representation of this map. The string representation consists of a list of key value mappings in the order returned by the entry entry iterator, which is enclosed in braces ("{}"). Adjacent mappings are separated by the characters "," (comma and space). Each mapping of key values โ€‹โ€‹is displayed as a key, followed by an equal sign ("="), followed by an associated value. Keys and values โ€‹โ€‹are converted to strings as by String.valueOf (Object).

+3
Nov 16 '17 at 16:12
source share

For me, this simple line worked well:

 Arrays.toString(map.entrySet().toArray()) 
+2
Sep 17 '18 at 12:32
source share

If the map contains the collection as a value, other answers require additional efforts to convert them into strings, such as Arrays.deepToString(value.toArray()) (if it is a map of list values), etc.

I often came across these problems and came across a common function for printing all objects using ObjectMappers . This is very convenient in all places, especially during experiments, and I would recommend that you choose this method.

 import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; public static String convertObjectAsString(Object object) { String s = ""; ObjectMapper om = new ObjectMapper(); try { om.enable(SerializationFeature.INDENT_OUTPUT); s = om.writeValueAsString(object); } catch (Exception e) { log.error("error converting object to string - " + e); } return s; } 
+1
Jan 6 '17 at 0:14
source share

You can use the Entry class to read HashMap easily.

 for(Map.Entry<TypeKey, TypeKey> temp : example.entrySet()){ System.out.println(temp.getValue()); // Or something as per temp defination. can be used } 
0
Dec 30 '16 at 11:02
source share

Useful for fast printing entries in HashMap.

 System.out.println(Arrays.toString(map.entrySet().toArray())); 
0
Mar 04 '19 at 4:06
source share
 map.forEach((key, value) -> System.out.println(key + " " + value)); 

Using Java 8 Features

0
Jun 10 '19 at 16:20
source share



All Articles