Java 10 – Using var with HashMap and Different Ways to Iterate
In Java 10, the var keyword for local variable type inference works seamlessly with collections like HashMap. This tutorial shows you how to declare a Map using var and then iterate over it using five different approaches — from the classic entrySet loop to modern lambda expressions and streams.
If you are new to the var keyword, it was introduced in Java 10 (JEP 286) and allows the compiler to infer the type of a local variable from its initializer. The variable is still statically typed — var just removes the redundancy of writing the type twice.
Prerequisites
- Java 10 or later (run
java -versionto check) - Familiarity with
HashMapand basic Java collections - Optional: understanding of Java 8 lambda expressions
Setting Up the HashMap with var
package com.java9r;
import java.util.HashMap;
import java.util.Map;
/**
* Java 10 – HashMap declared with var and iterated using multiple approaches.
*/
public class Java10MapWithVar {
public static void main(String[] args) {
// 'var' infers the type as HashMap<String, Object>
var products = new HashMap<String, Object>();
products.put("Id", "100");
products.put("Name", "Laptop Pro");
products.put("Price", 75000.00);
products.put("Quantity", 50);
System.out.println("=== Product Details ===\n");
// -------------------------------------------------------
// Method 1 : Enhanced for-loop over entrySet()
// Most readable; use when you need both key and value
// -------------------------------------------------------
System.out.println("1) Enhanced for-loop (entrySet):");
for (var entry : products.entrySet()) {
System.out.println(" " + entry.getKey() + " = " + entry.getValue());
}
// -------------------------------------------------------
// Method 2 : Enhanced for-loop over keySet()
// Slightly less efficient; use when you only need keys
// -------------------------------------------------------
System.out.println("\n2) Enhanced for-loop (keySet):");
for (var key : products.keySet()) {
System.out.println(" " + key + " = " + products.get(key));
}
// -------------------------------------------------------
// Method 3 : Iterator (classic Java style)
// Useful when you need to remove entries during iteration
// -------------------------------------------------------
System.out.println("\n3) Iterator:");
var iterator = products.entrySet().iterator();
while (iterator.hasNext()) {
var entry = iterator.next();
System.out.println(" " + entry.getKey() + " : " + entry.getValue());
}
// -------------------------------------------------------
// Method 4 : forEach() with lambda (Java 8+)
// Concise; perfect for read-only iteration
// -------------------------------------------------------
System.out.println("\n4) forEach() lambda:");
products.forEach((key, value) ->
System.out.println(" " + key + " -> " + value)
);
// -------------------------------------------------------
// Method 5 : Stream API (Java 8+)
// Best when you need to filter, sort, or transform entries
// -------------------------------------------------------
System.out.println("\n5) Stream API (sorted by key):");
products.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.forEach(e ->
System.out.println(" " + e.getKey() + " = " + e.getValue())
);
}
}
Expected Output
=== Product Details ===
1) Enhanced for-loop (entrySet):
Id = 100
Name = Laptop Pro
Price = 75000.0
Quantity = 50
2) Enhanced for-loop (keySet):
Id = 100
Name = Laptop Pro
Price = 75000.0
Quantity = 50
3) Iterator:
Id : 100
Name : Laptop Pro
Price : 75000.0
Quantity : 50
4) forEach() lambda:
Id -> 100
Name -> Laptop Pro
Price -> 75000.0
Quantity -> 50
5) Stream API (sorted by key):
Id = 100
Name = Laptop Pro
Price = 75000.0
Quantity = 50
Note: HashMap does not guarantee insertion order. The order of output in methods 1–4 may vary. Method 5 sorts entries alphabetically by key.
When to Use Each Method
| Method | Best For | Supports Remove? |
|---|---|---|
| entrySet for-each | Read key + value, most common | No (ConcurrentModificationException) |
| keySet for-each | When you only need keys | No |
| Iterator | Removing entries during loop | Yes (iterator.remove()) |
| forEach lambda | Concise read-only pass | No |
| Stream API | Filter / sort / transform | No (collect to new map) |
How var Helps with Map.Entry
Without var, iterating with entrySet forces you to write the full generic type:
// Verbose – pre Java 10
for (Map.Entry<String, Object> entry : products.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
// Clean – Java 10 with var
for (var entry : products.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
Both compile to identical bytecode. The var version is easier to type and read, especially when the value type is complex like Map.Entry<String, List<Product>>.
Removing Entries Safely Using Iterator
// Safe removal during iteration – use Iterator, not for-each
var iterator = products.entrySet().iterator();
while (iterator.hasNext()) {
var entry = iterator.next();
// Remove entries with null value
if (entry.getValue() == null) {
iterator.remove(); // safe removal
}
}
Summary
Java 10's var reduces the verbosity of HashMap declarations and loop variables without any loss of type safety. For simple iteration, the enhanced for-loop over entrySet() is the most readable option. Use forEach with a lambda for concise one-liner passes, and the Stream API when you need sorting or filtering. Use the explicit Iterator only when you need to remove entries during iteration.
See also: Java 10 ArrayList with var and Java 10 Set with var for more examples in this series.
Comments