Sets, Queues & Iterators
Sets store unique elements (no duplicates). Queues follow FIFO order (First-In, First-Out). Iterators provide a safe way to traverse and modify collections. Together, these tools handle diverse data organization needs. This is a foundational concept in enterprise application development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world Java experience. Take your time with each section and practice the examples
40 min•By Priygop Team•Last updated: Feb 2026
Sets, Queues & Iterators
Example
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
// === HASHSET — unique elements, no order ===
System.out.println("=== HashSet ===");
HashSet<String> languages = new HashSet<>();
languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
languages.add("Java"); // Duplicate — ignored!
languages.add("Python"); // Duplicate — ignored!
System.out.println("Languages: " + languages);
System.out.println("Size: " + languages.size()); // 3 (no dups)
// Set operations
HashSet<String> webLangs = new HashSet<>();
webLangs.add("JavaScript");
webLangs.add("HTML");
webLangs.add("CSS");
// Intersection
HashSet<String> common = new HashSet<>(languages);
common.retainAll(webLangs);
System.out.println("Common: " + common);
// Union
HashSet<String> allLangs = new HashSet<>(languages);
allLangs.addAll(webLangs);
System.out.println("All: " + allLangs);
// === QUEUE — First-In, First-Out ===
System.out.println("\n=== Queue ===");
Queue<String> queue = new LinkedList<>();
queue.add("Customer 1");
queue.add("Customer 2");
queue.add("Customer 3");
System.out.println("Queue: " + queue);
System.out.println("Next: " + queue.peek()); // Look, don't remove
System.out.println("Served: " + queue.poll()); // Remove first
System.out.println("After: " + queue);
// === ITERATOR — safe traversal ===
System.out.println("\n=== Iterator ===");
ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8));
Iterator<Integer> it = numbers.iterator();
while (it.hasNext()) {
int num = it.next();
if (num % 2 == 0) {
it.remove(); // Safely remove even numbers
}
}
System.out.println("Odd numbers: " + numbers);
}
}Try It Yourself: Unique Word Counter
Try It Yourself: Unique Word CounterJava
Java Editor
✓ ValidTab = 2 spaces
Java|37 lines|1488 chars|✓ Valid syntax
UTF-8