Java TreeMap entrySet() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.util.TreeMap

Definition

In Java, entrySet() returns a Set<Map.Entry<K, V>> view of a TreeMap. Each element is one key/value pair, and iteration visits them in ascending key order. It is the most efficient way to loop over keys and values together.

Unlike the snapshots from firstEntry() and friends, the entries you get while iterating are the real tree nodes: setValue changes the value in the map. The set itself is a live view that supports removal but not addition.

An instance method of java.util.TreeMap, part of TreeMap since Java 1.2. A TreeMap keeps its key/value pairs sorted by key in a red-black tree, so lookups and updates take O(log n) time; it is not thread-safe.

Syntax

The classic loop over keys and values:

Java
TreeMap<String, Integer> stock = new TreeMap<>();
for (Map.Entry<String, Integer> e : stock.entrySet()) {
    String key = e.getKey();
    Integer value = e.getValue();
}
CallWhat it does
map.entrySet()Live view of all entries, in key order.
e.setValue(v)Replaces the value in the map (during iteration).
map.entrySet().removeIf(p)Removes every entry that matches.

Looping over entrySet() avoids the extra O(log n) get call per key that a keySet() loop needs.

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

// Declared in Map<K, V> and SortedMap<K, V>

Parameters

ParameterDescription
(none)entrySet takes no parameters.

Return Value

Return ValueDescription
Set<Map.Entry<K, V>>A live view of the mappings, iterated in ascending key order.

Compare with Similar Methods

Ways to visit every mapping:

MethodHow it differs
forEach((k, v) -> ...)Java 8 lambda over keys and values.
replaceAll(f)Recomputes every value in one call.
keySet()Keys only.
HashMap.entrySet()Same API, unordered.

Java Examples

Example 1 — Print an Inventory Report

Each Map.Entry provides the item and its count in one step.

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

public class TreeMapEntrySetInventory {
    public static void main(String[] args) {
        TreeMap<String, Integer> inventory = new TreeMap<>();
        inventory.put("pens", 12);
        inventory.put("ink", 3);
        inventory.put("paper", 500);

        for (Map.Entry<String, Integer> e : inventory.entrySet()) {
            System.out.println(e.getKey() + " -> " + e.getValue());
        }
        System.out.println("entries: " + inventory.entrySet().size());
    }
}

How It Works

  1. Both halves at hand. getKey() and getValue() read the item and count from the same entry, with no second lookup.
  2. Alphabetical report. The rows appear as ink, paper, pens because the entry set follows the sorted keys.
  3. One entry per key. The set's size() equals the map's size, 3.

Example 2 — Give Everyone a 10% Raise With setValue()

setValue on an iterated entry writes the new value into the map and returns the old one.

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

public class TreeMapEntrySetRaise {
    public static void main(String[] args) {
        TreeMap<String, Integer> salaries = new TreeMap<>();
        salaries.put("Bo", 4200);
        salaries.put("Ann", 3000);

        for (Map.Entry<String, Integer> e : salaries.entrySet()) {
            int old = e.setValue(e.getValue() * 110 / 100);
            System.out.println(e.getKey() + ": " + old + " -> " + e.getValue());
        }
        System.out.println(salaries);
    }
}

How It Works

  1. Integer arithmetic. Multiplying by 110 before dividing by 100 keeps the calculation exact for these amounts: 3000 becomes 3300 and 4200 becomes 4620.
  2. setValue returns the previous value. old receives 3000 and 4200, so each line shows the before and after.
  3. Safe during the loop. Replacing values is not a structural change, so no ConcurrentModificationException occurs and the map holds the raised salaries.

Example 3 — Drop Low-Stock Items With removeIf()

The predicate sees whole entries, so it can test keys, values, or both.

Java
import java.util.TreeMap;

public class TreeMapEntrySetRemoveIf {
    public static void main(String[] args) {
        TreeMap<String, Integer> stock = new TreeMap<>();
        stock.put("apples", 40);
        stock.put("kiwis", 4);
        stock.put("pears", 9);
        stock.put("plums", 15);

        System.out.println("removed low stock: " + stock.entrySet().removeIf(e -> e.getValue() < 10));
        System.out.println("left: " + stock);
        System.out.println("removed z-items: " + stock.entrySet().removeIf(e -> e.getKey().startsWith("z")));
    }
}

How It Works

  1. Test on the value. Kiwis (4) and pears (9) are under 10, so both entries are removed and the call returns true.
  2. Removal reaches the map. The entry set is a view; stock now holds only apples and plums.
  3. Test on the key. No fruit starts with "z", so the second removeIf changes nothing and returns false.

Frequently Asked Questions

Loop over map.entrySet() with a Map.Entry variable and call getKey() and getValue() on it. The loop visits every pair in ascending key order.
Yes. e.setValue(newValue) writes to the map and is safe during iteration.
A key was added or removed through the map while the loop was running. Use Iterator.remove() or entrySet().removeIf(...) instead.
Yes. The entry loop reads each value directly; the keySet loop does an extra O(log n) lookup per key.
No. add() throws UnsupportedOperationException. Use put on the map.

Next: firstEntry()

Read the pair with the smallest key, or null when empty.

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

10 people found this page helpful