180

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,009
  • 4
  • 25
  • 38
Unknown user
  • 44,551
  • 16
  • 38
  • 42
  • 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](http://download.oracle.com/javase/6/docs/api/java/util/Map.html#size()): "Returns the number of key-value mappings in this map. If the map contains more than `Integer.MAX_VALUE` elements, returns `Integer.MAX_VALUE`." – Adam Paynter May 07 '11 at 09:18
  • Your code is looking for Values in Keys - which is not correct. Either look for key in Keys or value in Values – d-live May 07 '11 at 09: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. – Jesper May 07 '11 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. – HoldOffHunger Jun 04 '17 at 22:47

17 Answers17

215

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
  • 363
  • 3
  • 6
  • 17
Ken Chan
  • 84,777
  • 26
  • 143
  • 172
119

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}]
nicovank
  • 3,157
  • 1
  • 21
  • 42
Mingfei
  • 1,459
  • 1
  • 10
  • 12
  • 32
    Just do as: ```System.out.println(map);```, output: ```{b=2, a=1}``` – Mingfei Oct 20 '17 at 01:25
  • Yeah... one more similar output: `System.out.println(map.toString());` – Yo Apps Jan 23 '19 at 13:56
  • 1
    @yoapps beware of NPE in this case. That's why I avoid the `.toString` when possible. – Maroun Aug 03 '19 at 08:38
  • 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! – Yo Apps Aug 06 '19 at 08:13
45

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());
}
user000001
  • 32,226
  • 12
  • 81
  • 108
17

To print both key and value, use the following:

for (Object objectName : example.keySet()) {
   System.out.println(objectName);
   System.out.println(example.get(objectName));
 }
Stylianos Gakis
  • 862
  • 8
  • 19
Venkatesh
  • 577
  • 1
  • 7
  • 16
15

You have several options

Adam Paynter
  • 46,244
  • 33
  • 149
  • 164
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
14

For me this simple one line worked well:

Arrays.toString(map.entrySet().toArray())
KayV
  • 12,987
  • 11
  • 98
  • 148
11
map.forEach((key, value) -> System.out.println(key + " " + value));

Using java 8 features

Th0rgal
  • 703
  • 8
  • 27
  • 4
    While this code may solve the question, [including an explanation](https://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) 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. – Dave Jun 10 '19 at 17:38
10

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

arjun gulyani
  • 669
  • 2
  • 8
  • 23
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.

Maroun
  • 94,125
  • 30
  • 188
  • 241
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!

davmac
  • 20,150
  • 1
  • 40
  • 68
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

    }
}
ahmet
  • 1,085
  • 2
  • 16
  • 32
6

Useful to quickly print entries in a HashMap

System.out.println(Arrays.toString(map.entrySet().toArray()));
ThReSholD
  • 668
  • 10
  • 15
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());
}
Alex Weitz
  • 3,199
  • 4
  • 34
  • 57
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());
}
anand krish
  • 4,281
  • 4
  • 44
  • 47
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));
CodingBee
  • 1,011
  • 11
  • 8
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;
}
Alex Weitz
  • 3,199
  • 4
  • 34
  • 57
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
}
Sagar Chilukuri
  • 1,430
  • 2
  • 17
  • 29