Java 10 – Using var with HashSet and Different Ways to Iterate
A Set is a collection that contains no duplicate elements. In Java, the most commonly used implementation is HashSet, which offers O(1) average performance for add, remove, and contains operations. Java 10's var keyword lets you declare a HashSet without repeating the type, making the code cleaner and easier to maintain.
This tutorial shows how to create a Set with var and iterate over it using four different approaches, with practical notes on when each is appropriate.
What is a HashSet?
HashSet implements the Set interface and stores elements in a hash table. Key characteristics:
- No duplicates — adding the same element twice has no effect
- No guaranteed order — iteration order can change between runs
- Allows one null
- Not thread-safe — use
Collections.synchronizedSet()if needed
Use a Set when you need a collection of unique values and order does not matter. For ordered sets, use LinkedHashSet (insertion order) or TreeSet (sorted order).
Complete Example
package com.java9r;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Java 10 – HashSet declared with var, iterated four ways.
*/
public class Java10SetWithVar {
public static void main(String[] args) {
// var infers HashSet<String>
var products = new HashSet<String>();
products.add("Laptop");
products.add("Smartphone");
products.add("Tablet");
products.add("Monitor");
products.add("Keyboard");
products.add("Laptop"); // duplicate – silently ignored
System.out.println("Total unique products: " + products.size()); // 5
// -------------------------------------------------------
// Method 1 : Enhanced for-each
// Simplest; use for read-only, order doesn't matter
// -------------------------------------------------------
System.out.println("\n1) Enhanced for-each:");
for (var product : products) {
System.out.println(" " + product);
}
// -------------------------------------------------------
// Method 2 : Iterator
// Use when you need to remove elements during iteration
// -------------------------------------------------------
System.out.println("\n2) Iterator:");
var iterator = products.iterator();
while (iterator.hasNext()) {
var product = iterator.next();
System.out.println(" " + product);
}
// -------------------------------------------------------
// Method 3 : forEach() with lambda
// Concise; great for printing or simple transforms
// -------------------------------------------------------
System.out.println("\n3) forEach() lambda:");
products.forEach(p -> System.out.println(" " + p.toUpperCase()));
// -------------------------------------------------------
// Method 4 : Stream API
// Best for filter, sort, map, collect operations
// -------------------------------------------------------
System.out.println("\n4) Stream API (sorted):");
products.stream()
.sorted()
.forEach(p -> System.out.println(" " + p));
// Demonstrate duplicate prevention
System.out.println("\n--- Duplicate Check ---");
boolean added = products.add("Laptop"); // already exists
System.out.println("'Laptop' added again: " + added); // false
System.out.println("Set size unchanged: " + products.size()); // still 5
// Find intersection of two sets
var wishlist = new HashSet<String>();
wishlist.add("Laptop");
wishlist.add("Speaker");
wishlist.add("Tablet");
// retainAll() modifies in place – work on a copy
var available = new HashSet<>(products);
available.retainAll(wishlist);
System.out.println("\nWishlist items in stock: " + available);
// Convert set to sorted list
var sortedList = products.stream()
.sorted()
.collect(Collectors.toList());
System.out.println("\nSorted list from set: " + sortedList);
}
}
Expected Output
Total unique products: 5
1) Enhanced for-each:
Monitor
Keyboard
Laptop
Smartphone
Tablet
2) Iterator:
Monitor
Keyboard
Laptop
Smartphone
Tablet
3) forEach() lambda:
MONITOR
KEYBOARD
LAPTOP
SMARTPHONE
TABLET
4) Stream API (sorted):
Keyboard
Laptop
Monitor
Smartphone
Tablet
--- Duplicate Check ---
'Laptop' added again: false
Set size unchanged: 5
Wishlist items in stock: [Laptop, Tablet]
Sorted list from set: [Keyboard, Laptop, Monitor, Smartphone, Tablet]
Note: The iteration order of HashSet is not guaranteed. Methods 1–3 may print items in a different order on your machine.
When to Use HashSet, LinkedHashSet, or TreeSet
| Set Type | Order | Null | Performance | Best For |
|---|---|---|---|---|
| HashSet | None | One null | O(1) add/remove | Fast lookup, no order needed |
| LinkedHashSet | Insertion order | One null | Slightly slower | Unique items, preserve order |
| TreeSet | Natural/Comparator | No null | O(log n) | Sorted unique items |
Removing Elements Safely
// Safe removal during iteration using Iterator
var iter = products.iterator();
while (iter.hasNext()) {
var p = iter.next();
if (p.length() > 7) {
iter.remove(); // removes elements with names longer than 7 chars
}
}
// Cleaner alternative: removeIf (Java 8+)
products.removeIf(p -> p.length() > 7);
Summary
Java 10's var makes HashSet declarations more concise. The set's core guarantee is uniqueness — adding duplicates silently does nothing. For simple iteration without ordering requirements, the enhanced for-each or forEach lambda are the most readable options. When you need sorted output, use TreeSet directly or pipe through the Stream API. Use Iterator.remove() or removeIf() to safely remove elements during iteration.
Comments