Java HashMap entrySet() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
HashMap

Definition

In Java, entrySet() returns a Set<Map.Entry<K, V>> with one entry per mapping in the HashMap. Each Map.Entry gives you the key with getKey() and the value with getValue().

It is the most efficient way to loop over a map when you need both parts, because no extra get lookup is required. The set is a live view: entry.setValue(v) writes into the map, and removing an entry removes the mapping.

An instance method of java.util.HashMap (class since Java 1.2): a hash table of key/value pairs with no guaranteed order, one null key, any number of null values, and no thread safety.

Syntax

No arguments; returns a live Set of entries.

Java
for (Map.Entry<String, Integer> e : map.entrySet()) {
    String key = e.getKey();
    Integer value = e.getValue();
    e.setValue(value + 1);     // writes into the map
}
CallWhat it does
e.getKey()The key of this entry.
e.getValue()The current value of this entry.
e.setValue(v)Replaces the value in the map; returns the old one.
map.entrySet().removeIf(test)Removes every mapping whose entry passes the test.

Map.Entry is a nested interface, so write Map.Entry<K, V> (with import java.util.Map;) or import java.util.Map.Entry separately.

Library declarations
Java
// java.util.HashMap<K, V>
public Set<Map.Entry<K, V>> entrySet()

// Map.Entry<K, V>
K getKey()
V getValue()
V setValue(V value)

Parameters

ParameterDescription
NoneentrySet() takes no parameters.

Return Value

Return ValueDescription
Set<Map.Entry<K, V>>A live view of the mappings. Supports removal and setValue on its entries, but not add.

Compare with Similar Methods

Looping over a HashMap:

MethodHow it differs
forEach((k, v) -> ...)Shorter loop; cannot remove entries.
keySet()Keys only; needs get for values.
values()Values only.
replaceAll(f)Updates every value without an explicit loop.

Java Examples

Example 1 — Print Subject Marks with Map.Entry

The standard loop over keys and values, followed by the entry set printed as a whole.

Java
import java.util.HashMap;
import java.util.Map;

public class HashMapEntrySetDemo {
    public static void main(String[] args) {
        Map<String, Integer> marks = new HashMap<>();
        marks.put("Maths", 88);
        marks.put("Physics", 76);
        marks.put("History", 91);

        for (Map.Entry<String, Integer> entry : marks.entrySet()) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
        System.out.println("as a set: " + marks.entrySet());
    }
}

How It Works

  1. Entry type. Each element is a Map.Entry<String, Integer>, a small object holding one subject and its mark.
  2. Both parts, one pass. getKey() and getValue() read the pair directly, with no second lookup in the map.
  3. Not insertion order. Physics was added second but printed last; entries follow the buckets their keys hash to.
  4. Entry text form. Printing the set shows each entry as key=value inside square brackets.

Example 2 — Raise Every Price with setValue

Add 10% to each price in place, then print a sorted copy.

Java
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class HashMapEntrySetSetValue {
    public static void main(String[] args) {
        Map<String, Integer> prices = new HashMap<>();
        prices.put("pen", 20);
        prices.put("notebook", 50);
        prices.put("bag", 400);

        for (Map.Entry<String, Integer> e : prices.entrySet()) {
            e.setValue(e.getValue() + e.getValue() / 10);
        }
        System.out.println("after +10%: " + new TreeMap<>(prices));
    }
}

How It Works

  1. Write-through entries. setValue on an entry from entrySet() changes the value stored in prices itself.
  2. Not a structural change. Replacing values does not add or remove keys, so it is safe inside the loop and causes no ConcurrentModificationException.
  3. Integer arithmetic. Each price grows by a tenth of itself: 20 + 2, 50 + 5, and 400 + 40.
  4. Sorted for display. The TreeMap copy prints the items alphabetically: bag, notebook, pen.

Example 3 — Expire Sessions with Iterator.remove()

Remove short sessions while looping, using the iterator, then remove one more with removeIf.

Java
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HashMapEntrySetRemove {
    public static void main(String[] args) {
        Map<String, Integer> sessions = new HashMap<>();
        sessions.put("s1", 5);
        sessions.put("s2", 42);
        sessions.put("s3", 0);
        sessions.put("s4", 17);

        Iterator<Map.Entry<String, Integer>> it = sessions.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Integer> e = it.next();
            if (e.getValue() < 10) {
                System.out.println("expire " + e.getKey());
                it.remove();
            }
        }
        System.out.println("active: " + sessions);

        sessions.entrySet().removeIf(e -> e.getKey().equals("s4"));
        System.out.println("after removeIf: " + sessions);
    }
}

How It Works

  1. Explicit iterator. Writing the loop with Iterator gives access to it.remove(), the one safe way to delete during a manual loop.
  2. Visit order. s3 and s4 hash to the first buckets of the table, so s3 is expired before s1 even though s1 was added first.
  3. No exception. it.remove() deletes the current entry and updates the iterator's bookkeeping, so the loop continues normally.
  4. Shorter form. entrySet().removeIf(...) runs the same iterator logic internally; here it removes the s4 session by key.

Frequently Asked Questions

Loop over map.entrySet() with Map.Entry when you need both keys and values. It avoids an extra get() for each key.
Call entry.setValue(newValue) on the entries from entrySet(). It writes into the map and is safe during iteration.
Use an explicit Iterator and call iterator.remove(), or use map.entrySet().removeIf(...). Calling map.remove() inside the loop usually causes ConcurrentModificationException.
No. A HashMap has no guaranteed order. Use LinkedHashMap for insertion order or TreeMap for sorted order.
key=value, for example Maths=88.

Next: forEach()

Run an action for every key and value.

forEach() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

14 people found this page helpful