186

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?

Ramesh R
7,0874 gold badges27 silver badges40 bronze badges
asked May 7, 2011 at 9:09
4
  • 2
    I recommend you become familiar with Java's documentation (it will answer many of your questions). For example, this is the documentation for Map's size() method: "Returns the number of key-value mappings in this map. If the map contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE." Commented May 7, 2011 at 9:18
  • Your code is looking for Values in Keys - which is not correct. Either look for key in Keys or value in Values Commented May 7, 2011 at 9:52
  • 2
    If it has 1 key / value it will ofcourse have size 1. But this does not have anything to do with zero-based indexing. Commented May 7, 2011 at 11:59
  • This is a good question. But there is an answer here provided here that can do this in one line, if you see Mingfei's solution. Commented Jun 4, 2017 at 22:47

17 Answers 17

228

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.forEach((key, value) -> System.out.println(key + " " + value));

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.

Saurabh Gupta
5373 gold badges7 silver badges21 bronze badges
answered May 7, 2011 at 9:13
Sign up to request clarification or add additional context in comments.

3 Comments

Or better yet: for (Map.Entry<String, String> entry : map.entrySet()) { ... }
Or even more compact: example.forEach((key, value) -> System.out.println("key + " | " + value));
What is "entry" is that a reference to something or a command word?
126

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}]
user2345
3,2271 gold badge24 silver badges44 bronze badges
answered Nov 3, 2015 at 3:55

4 Comments

Just do as: System.out.println(map);, output: {b=2, a=1}
Yeah... one more similar output: System.out.println(map.toString());
@yoapps beware of NPE in this case. That's why I avoid the .toString when possible.
Thats true. the NPE always lurks in such short cuts. I only wanted to show a similar out put.. I think especially when you're debugging to a log/console and you just wana peek into a map whose data you know isnt null. this is a quick fire! But if its code checking from scratch... then you're right, its tricky and in good programming context, it should be avoided!
47

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());
}
answered Jun 12, 2013 at 14:34

Comments

18

To print both key and value, use the following:

for (Object objectName : example.keySet()) {
 System.out.println(objectName);
 System.out.println(example.get(objectName));
 }
answered Oct 20, 2014 at 4:00

1 Comment

You are missing another bracket before the semi colon on the 3rd line.
16

You have several options

Adam Paynter
47.1k33 gold badges153 silver badges168 bronze badges
answered May 7, 2011 at 9:11

Comments

15

For me this simple one line worked well:

Arrays.toString(map.entrySet().toArray())
answered Sep 17, 2018 at 12:32

Comments

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

Using java 8 features

answered Jun 10, 2019 at 16:20

1 Comment

While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply.
11

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).

answered Nov 16, 2017 at 16:12

1 Comment

this looks to be the best answer from the ones above.
9

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!

answered May 7, 2011 at 9:12

Comments

9

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.

answered Feb 20, 2015 at 12:33

Comments

7

Useful to quickly print entries in a HashMap

System.out.println(Arrays.toString(map.entrySet().toArray()));
answered Mar 4, 2019 at 4:06

Comments

6

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
 }
}
answered Aug 29, 2016 at 8:26

Comments

4

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());
}
AlexW
3,4045 gold badges41 silver badges64 bronze badges
answered Jan 21, 2015 at 13:42

Comments

2

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());
}
answered Aug 17, 2021 at 15:00

Comments

2

Print a Map using java 8

Map<Long, String> productIdAndTypeMapping = new LinkedHashMap<>();
productIdAndTypeMapping.forEach((k, v) -> log.info("Product Type Key: " + k + ": Value: " + v));
answered Sep 7, 2021 at 13:46

Comments

1

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;
}
AlexW
3,4045 gold badges41 silver badges64 bronze badges
answered Jan 6, 2017 at 0:14

Comments

0

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
}
answered Dec 30, 2016 at 11:02

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.