Lesson 17: Collections: Set & Map
18 Jul 2026 1 min Swarnil Singhai
Set enforces uniqueness; Map stores key-value pairs — together they cover 'no duplicates' and 'lookup by key' use cases.
Real-time example
A URL shortener uses a HashMap<String, String> to map short codes to long URLs — O(1) average lookup on every redirect.
Map<String, String> urlStore = new HashMap<>();
urlStore.put("abc123", "https://example.com/very/long/path");
Set<String> usedCodes = urlStore.keySet();
System.out.println(usedCodes.contains("abc123")); // true
System.out.println(urlStore.get("abc123"));
What's happening
HashMap uses the key's hashCode()/equals() to bucket entries — that's how it achieves near O(1) lookups.
If you need insertion order, use LinkedHashMap; if you need sorted keys, use TreeMap.
Advertisement