Java 25 (LTS) reference · Map and HashMap Methods

Java Map entrySet() Method

Return the map's entries (key-value pairs) for looping over keys and values together.

Java 25 (LTS) Since Java 1.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

map.entrySet()

Return value

A Set<Map.Entry<K, V>> view.

Examples

Loop over keys and values
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> stock = new TreeMap<>(Map.of("mug", 12, "tea", 3, "kettle", 0));
        for (Map.Entry<String, Integer> e : stock.entrySet()) {
            System.out.println(e.getKey() + ": " + e.getValue());
        }
    }
}

Output

kettle: 0
mug: 12
tea: 3

Run this on your computer — see “Get Started” for setup.

forEach, keySet and values
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> stock = new TreeMap<>(Map.of("mug", 12, "tea", 3));
        stock.forEach((item, qty) -> System.out.println(item + " x" + qty));
        System.out.println(stock.keySet() + " " + stock.values());
    }
}

Output

mug x12
tea x3
[mug, tea] [12, 3]

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 1.0Added

Was this page helpful?