---
title: "Iterate through a HashMap"  
description: "Iterate through a HashMap"  
author: "Anonymous User"  
published: 2015-05-04  
updated: 2015-05-04  
canonical: https://www.mindstick.com/forum/23184/iterate-through-a-hashmap  
category: "java"  
tags: ["java"]  
reading_time: 1 minute  

---

# Iterate through a HashMap

What's the best way to iterate over the [items](https://www.mindstick.com/forum/33812/getting-number-of-items-selected-in-uicollectionview-in-ios) in a [HashMap](https://www.mindstick.com/forum/159211/what-are-the-differences-between-a-hashmap-and-a-hashtable-in-java)?

## Replies

### Reply by Anonymous User

Iterate through the entrySet like so:\

```
public static void printMap(Map mp) {    Iterator it = mp.entrySet().iterator();    while (it.hasNext()) {        Map.Entry pair = (Map.Entry)it.next();        System.out.println(pair.getKey() + " = " + pair.getValue());        it.remove(); // avoids a ConcurrentModificationException    }}
```

\
If you're only interested in the keys, you can iterate through the keySet() of the map:\

```
Map<String, Object> map = ...;for (String key : map.keySet()) {    // ...}
```

If you only need the values, use values():\

```
for (Object value : map.values()) {    // ...}
```


---

Original Source: https://www.mindstick.com/forum/23184/iterate-through-a-hashmap

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
