Printing HashMap In Java

JavaCollections

Java Problem Overview


I have a HashMap:

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

Now I would like to run through all the values and print them.

I wrote this:

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

It doesn't seem to work.

What is the problem?

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

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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}]

Solution 3 - Java

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());
}

Solution 4 - Java

To print both key and value, use the following:

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

Solution 5 - Java

You have several options

Solution 6 - Java

For me this simple one line worked well:

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

Solution 7 - Java

You want the value set, not the key set:

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

The code you give wouldn't even compile, which may be worth mentioning in future questions - "doesn't seem to work" is a bit vague!

Solution 8 - Java

Worth mentioning Java 8 approach, using BiConsumer and lambda functions:

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

example.forEach(consumer);

Assuming that you've overridden toString method of the two types if needed.

Solution 9 - Java

A simple print statement with the variable name which contains the reference of the Hash Map would 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 over-ridden in the AbstractMap class which is extended by the HashMap Class More 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 map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).

Solution 10 - Java

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

Using java 8 features

Solution 11 - Java

Java 8 new feature forEach style

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
		
	}
}

Solution 12 - Java

Useful to quickly print entries in a HashMap

System.out.println(Arrays.toString(map.entrySet().toArray()));

Solution 13 - Java

I did it using String map (if you're working with 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());
}

Solution 14 - Java

Using java 8 feature:

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

Using Map.Entry you can print like this:

 for(Map.Entry entry:map.entrySet())
{
    System.out.print(entry.getKey() + " : " + entry.getValue());
}

Traditional way to get all keys and values from the map, you have to follow this sequence:

  • Convert HashMap to MapSet to get set of entries in Map with entryset() method.:
    Set dataset = map.entrySet();
  • Get the iterator of this set:
    Iterator it = dataset.iterator();
  • Get Map.Entry from the iterator:
    Map.Entry entry = it.next();
  • use getKey() and getValue() methods of the Map.Entry to retrive keys and values.

Set dataset = (Set) map.entrySet();
Iterator it = dataset.iterator();
while(it.hasNext()){
    Map.Entry entry = mapIterator.next();
    System.out.print(entry.getKey() + " : " + entry.getValue());
}

Solution 15 - Java

Print a Map using java 8

Map<Long, String> productIdAndTypeMapping = new LinkedHashMap<>();
productIdAndTypeMapping.forEach((k, v) -> log.info("Product Type Key: " + k + ": Value: " + v));

Solution 16 - Java

If the map holds a collection as value, the other answers require additional effort to convert them as strings, such as Arrays.deepToString(value.toArray()) (if its a map of list values), etc.

I faced these issues quite often and came across the generic function to print all objects using ObjectMappers. This is quite handy at all the places, especially during experimenting things, and I would recommend you to choose this way.

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;
}

Solution 17 - Java

You can use 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
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUnknown userView Question on Stackoverflow
Solution 1 - JavaKen ChanView Answer on Stackoverflow
Solution 2 - JavaMingfeiView Answer on Stackoverflow
Solution 3 - Javauser000001View Answer on Stackoverflow
Solution 4 - JavaVenkateshView Answer on Stackoverflow
Solution 5 - JavaBozhoView Answer on Stackoverflow
Solution 6 - JavaKayVView Answer on Stackoverflow
Solution 7 - JavadavmacView Answer on Stackoverflow
Solution 8 - JavaMarounView Answer on Stackoverflow
Solution 9 - Javaarjun gulyaniView Answer on Stackoverflow
Solution 10 - JavaTh0rgalView Answer on Stackoverflow
Solution 11 - JavaahmetView Answer on Stackoverflow
Solution 12 - JavaThReSholDView Answer on Stackoverflow
Solution 13 - JavaEdson JúniorView Answer on Stackoverflow
Solution 14 - Javaanand krishView Answer on Stackoverflow
Solution 15 - JavaCodingBeeView Answer on Stackoverflow
Solution 16 - JavaThirukka KarnanView Answer on Stackoverflow
Solution 17 - JavaSagar ChilukuriView Answer on Stackoverflow