Set & Map Sorting
Custom sorting with Comparable and Comparator applied to Sets and Maps
- Sort objects stored in TreeSet and TreeMap using Comparable and Comparator
- Chain Comparator predicates for multi-field sorting
- Understand natural ordering vs imposed ordering
Set implementations, Map hierarchy, and Comparable vs Comparator.Table of Contents
- The Set Interface
- HashSet
- LinkedHashSet
- TreeSet
- Set Comparison Table
- The Map Interface
- Map Methods Reference
- HashMap
- LinkedHashMap
- TreeMap
- Hashtable
- Map Comparison Table
- Comparable vs Comparator
- Full JCF Hierarchy
- Interview Notes
- Summary & Quick Revision
- Practice Questions
1. The `Set` Interface
Definition
A Set is a Collection that contains no duplicate elements. It models the mathematical set abstraction.
Real-world Analogy
A bag of unique raffle tickets — adding a duplicate ticket has no effect.
How Duplicates Are Prevented
When set.add(element) is called, Java internally checks hashCode() + equals(). If an equal element exists, add() is silently ignored and returns false.
1Set<String> set = new HashSet<>();2System.out.println(set.add("Java")); // true3System.out.println(set.add("Java")); // false — duplicate4System.out.println(set.size()); // 1Hierarchy
Set vs List
| Feature | Set | List |
|---|---|---|
| Duplicates | ❌ | ✅ |
| Index-based access | ❌ | ✅ |
| Order guarantee | Depends on impl | ✅ Always insertion order |
2. HashSet
Key Characteristics
| Feature | Value |
|---|---|
| Backed by | HashMap internally |
| Order | ❌ No guaranteed order |
| Thread-safe | ❌ No |
| Null elements | ✅ One null allowed |
| Time complexity | O(1) average |
Internal Working
HashSet stores each element as a key in an internal HashMap with a dummy value. If put() returns a non-null (old dummy), a duplicate was attempted → add() returns false.
Code Example
1import java.util.*;2
3public class HashSetExample {4 public static void main(String[] args) {5 Set<String> fruits = new HashSet<>();6
7 System.out.println(fruits.add("Mango")); // true8 System.out.println(fruits.add("Apple")); // true9 System.out.println(fruits.add("Apple")); // false — duplicate10 System.out.println(fruits.add(null)); // true11 System.out.println(fruits.add(null)); // false — second null rejected12 System.out.println("Size: " + fruits.size()); // 313
14 // Order NOT guaranteed15 fruits.forEach(System.out::println);16
17 System.out.println(fruits.contains("Apple")); // true18 fruits.remove("Mango");19 System.out.println(fruits); // [null, Apple] (order may vary)20 }21}Time Complexity
| Operation | Average | Worst Case |
|---|---|---|
add / remove / contains | O(1) | O(log n) (Java 8+ tree bucket) |
| Iteration | O(n + capacity) | — |
Thread-Safe Version
Use ConcurrentHashMap.newKeySet() or Collections.synchronizedSet(new HashSet<>()).
3. LinkedHashSet
Key Characteristics
| Feature | Value |
|---|---|
| Backed by | LinkedHashMap (hash table + doubly linked list) |
| Order | ✅ Insertion order preserved |
| Thread-safe | ❌ No |
| Null elements | ✅ One null allowed |
Code Example
1import java.util.*;2
3public class LinkedHashSetExample {4 public static void main(String[] args) {5 Set<String> colors = new LinkedHashSet<>();6 colors.add("Red");7 colors.add("Green");8 colors.add("Blue");9 colors.add("Red"); // duplicate — ignored10 colors.add("Yellow");11
12 System.out.println(colors); // [Red, Green, Blue, Yellow] — always insertion order13 }14}4. TreeSet
Key Characteristics
| Feature | Value |
|---|---|
| Backed by | TreeMap (Red-Black Tree) |
| Order | ✅ Sorted (natural or custom comparator) |
| Thread-safe | ❌ No |
| Null elements | ❌ NOT allowed — NullPointerException |
| Time complexity | O(log n) for all operations |
TreeSet does NOT allow null because it must compare elements, and comparing null is undefined.Internal Working Red-Black Tree
A self-balancing BST. In-order traversal gives elements in sorted order. Height stays O(log n), guaranteeing O(log n) operations.
1Insert 5, 3, 7, 1, 4:2 53 / \4 3 75 / \6 1 47In-order: 1 3 4 5 7 ← sorted outputCode Example
1import java.util.*;2
3public class TreeSetExample {4 public static void main(String[] args) {5 TreeSet<Integer> nums = new TreeSet<>();6 nums.add(5); nums.add(3); nums.add(7);7 nums.add(1); nums.add(4); nums.add(3); // duplicate ignored8
9 System.out.println(nums); // [1, 3, 4, 5, 7]10 System.out.println(nums.first()); // 111 System.out.println(nums.last()); // 712 System.out.println(nums.floor(4)); // 4 (greatest ≤ 4)13 System.out.println(nums.ceiling(4)); // 4 (smallest ≥ 4)14 System.out.println(nums.lower(4)); // 3 (strictly < 4)15 System.out.println(nums.higher(4));// 5 (strictly > 4)16 System.out.println(nums.headSet(4)); // [1, 3] (< 4)17 System.out.println(nums.tailSet(4)); // [4, 5, 7] (≥ 4)18 System.out.println(nums.subSet(2, 6)); // [3, 4, 5] (2 incl → 6 excl)19
20 // Custom (descending) order21 TreeSet<Integer> desc = new TreeSet<>(Comparator.reverseOrder());22 desc.addAll(nums);23 System.out.println(desc); // [7, 5, 4, 3, 1]24 }25}Output
1[1, 3, 4, 5, 7]2137445463758[1, 3]9[4, 5, 7]10[3, 4, 5]11[7, 5, 4, 3, 1]Extra SortedSet / NavigableSet Methods
| Method | Description |
|---|---|
first() / last() | Smallest / largest |
floor(e) / ceiling(e) | Greatest ≤ e / Smallest ≥ e |
lower(e) / higher(e) | Strictly < e / Strictly > e |
headSet(e) | View of elements < e |
tailSet(e) | View of elements ≥ e |
subSet(from, to) | from inclusive, to exclusive |
pollFirst() / pollLast() | Remove and return smallest/largest |
descendingSet() | Reverse-order view |
5. Set Comparison Table
| Feature | HashSet | LinkedHashSet | TreeSet |
|---|---|---|---|
| Internal structure | HashMap | LinkedHashMap | Red-Black Tree |
| Order | ❌ None | ✅ Insertion | ✅ Sorted |
| Null allowed | ✅ One | ✅ One | ❌ No |
add/remove/contains | O(1) avg | O(1) avg | O(log n) |
| When to use | Fast lookup, no order | Fast lookup + order | Sorted access, range queries |
6. The `Map` Interface
Overview
Map stores key-value pairs. It is a completely separate hierarchy from Collection — Map does NOT extend Collection or Iterable.
Why Map Is NOT Under Collection
Collection | Map |
|---|---|
| Single elements | Key-value pairs |
add(E e) — one param | put(K, V) — two params |
| Iterate over elements | Iterate over entries/keys/values |
Forcing Map under Collection would break the Collection contract.
Hierarchy
7. Map Methods Reference
Core Methods
| Method | Return | Description |
|---|---|---|
put(K, V) | V | Insert/update; returns previous value or null |
get(key) | V | Returns value; null if not found |
getOrDefault(key, def) | V | Returns value or def if not found |
remove(key) | V | Removes and returns value |
containsKey(key) | boolean | Key exists? |
containsValue(val) | boolean | Any key maps to this value? |
putIfAbsent(K, V) | V | Puts only if key NOT present |
replace(K, V) | V | Replaces only if key IS present |
size() / isEmpty() / clear() | — | Standard collection ops |
Iteration Methods
| Method | Returns | Description |
|---|---|---|
keySet() | Set | All keys |
values() | Collection | All values |
entrySet() | Set | All key-value pairs (preferred for iteration) |
forEach(BiConsumer) | void | Lambda iteration (Java 1.8) |
Three Ways to Iterate a Map
1Map<String, Integer> scores = new HashMap<>();2scores.put("Alice", 95); scores.put("Bob", 87); scores.put("Charlie", 92);3
4// Method 1: keySet() — two lookups per entry (less efficient)5for (String key : scores.keySet()) {6 System.out.println(key + " → " + scores.get(key));7}8
9// Method 2: entrySet() — one lookup per entry (PREFERRED)10for (Map.Entry<String, Integer> entry : scores.entrySet()) {11 System.out.println(entry.getKey() + " → " + entry.getValue());12}13
14// Method 3: forEach lambda (Java 1.8)15scores.forEach((k, v) -> System.out.println(k + " → " + v));entrySet() when you need both key and value. keySet() + get() performs two hash lookups per entry.8. HashMap
Key Characteristics
| Feature | Value |
|---|---|
| Backed by | Hash table (array of buckets) |
| Key order | ❌ No guaranteed order |
| Thread-safe | ❌ No |
| Null key | ✅ One null key |
| Null values | ✅ Multiple null values |
| Duplicate keys | ❌ — new value overwrites old |
Internal Working (Java 8+)
1put("Alice", 95):21. hashCode("Alice") → integer hash32. hash % capacity → bucket index43. Bucket empty? → store directly54. Bucket occupied?6 - Same key? → overwrite value7 - Different key (collision)?8 chain ≤ 8 entries → linked list9 chain > 8 entries → Red-Black Tree (O(log n) worst case)Code Example
1import java.util.*;2
3public class HashMapExample {4 public static void main(String[] args) {5 Map<String, Integer> map = new HashMap<>();6
7 map.put("Alice", 95);8 map.put("Bob", 87);9 map.put("Charlie", 92);10
11 // put() returns previous value12 Integer old = map.put("Alice", 99);13 System.out.println("Old: " + old); // 9514 System.out.println("New: " + map.get("Alice")); // 9915
16 System.out.println(map.get("Diana")); // null (not found)17 System.out.println(map.getOrDefault("Diana", 0)); // 018
19 System.out.println(map.containsKey("Bob")); // true20 System.out.println(map.containsValue(100)); // false21
22 map.putIfAbsent("Bob", 100); // Bob exists → no change23 map.putIfAbsent("Diana", 78); // Diana absent → inserted24 System.out.println(map.get("Bob")); // 8725 System.out.println(map.get("Diana")); // 7826
27 map.remove("Charlie");28 System.out.println(map.containsKey("Charlie")); // false29
30 // Null key and null value allowed31 map.put(null, 50);32 map.put("Zero", null);33 System.out.println(map.get(null)); // 5034 System.out.println(map.get("Zero")); // null35
36 map.clear();37 System.out.println(map.isEmpty()); // true38 }39}Time Complexity
| Operation | Average | Worst |
|---|---|---|
put / get / remove / containsKey | O(1) | O(log n) |
containsValue | O(n) | O(n) |
| Iteration | O(n + capacity) | — |
Thread-Safe Versions
| Variant | Notes |
|---|---|
HashMap | Not thread-safe |
Collections.synchronizedMap(new HashMap<>()) | Coarse lock; every method synchronized |
ConcurrentHashMap | Preferred — fine-grained bucket-level locking; high concurrency |
Hashtable | Legacy; avoid |
9. LinkedHashMap
Key Characteristics
| Feature | Value |
|---|---|
| Backed by | HashMap + doubly linked list |
| Key order | ✅ Insertion order (default) OR access order (optional) |
| Thread-safe | ❌ No |
| Null key | ✅ One |
Code Example Insertion Order
1import java.util.*;2
3public class LinkedHashMapExample {4 public static void main(String[] args) {5 Map<String, Integer> map = new LinkedHashMap<>();6 map.put("Charlie", 92);7 map.put("Alice", 95);8 map.put("Bob", 87);9
10 // Always prints in insertion order11 map.forEach((k, v) -> System.out.println(k + " → " + v));12 // Charlie → 9213 // Alice → 9514 // Bob → 8715 }16}Access-Order Mode (LRU Cache)
Constructor LinkedHashMap(capacity, loadFactor, true) enables access order — most recently accessed entry moves to the end. Override removeEldestEntry() to auto-evict.
1// accessOrder = true2Map<String, Integer> lru = new LinkedHashMap<>(16, 0.75f, true);3lru.put("A", 1); lru.put("B", 2); lru.put("C", 3);4// Order: A → B → C5
6lru.get("A"); // Access A → A moves to end7// Order: B → C → A8System.out.println(lru.keySet()); // [B, C, A]10. TreeMap
Key Characteristics
| Feature | Value |
|---|---|
| Backed by | Red-Black Tree |
| Key order | ✅ Sorted by key (natural or comparator) |
| Thread-safe | ❌ No |
| Null keys | ❌ NOT allowed |
| Null values | ✅ Allowed |
| Time complexity | O(log n) all key operations |
Code Example
1import java.util.*;2
3public class TreeMapExample {4 public static void main(String[] args) {5 TreeMap<String, Integer> map = new TreeMap<>();6 map.put("Charlie", 92);7 map.put("Alice", 95);8 map.put("Bob", 87);9 map.put("Diana", 78);10
11 // Always sorted by key (alphabetical for String)12 map.forEach((k, v) -> System.out.println(k + " → " + v));13 // Alice → 95, Bob → 87, Charlie → 92, Diana → 7814
15 System.out.println(map.firstKey()); // Alice16 System.out.println(map.lastKey()); // Diana17 System.out.println(map.lowerKey("Bob")); // Alice (strictly < "Bob")18 System.out.println(map.higherKey("Bob")); // Charlie (strictly > "Bob")19 System.out.println(map.headMap("C")); // {Alice=95, Bob=87}20 System.out.println(map.tailMap("C")); // {Charlie=92, Diana=78}21 System.out.println(map.subMap("B", "D")); // {Bob=87, Charlie=92}22 }23}Output
1Alice → 952Bob → 873Charlie → 924Diana → 785Alice6Diana7Alice8Charlie9{Alice=95, Bob=87}10{Charlie=92, Diana=78}11{Bob=87, Charlie=92}NavigableMap Extra Methods
| Method | Description |
|---|---|
firstKey() / lastKey() | Smallest / largest key |
floorKey(k) / ceilingKey(k) | Greatest ≤ k / Smallest ≥ k |
lowerKey(k) / higherKey(k) | Strictly < k / Strictly > k |
headMap(toKey) | Keys < toKey |
tailMap(fromKey) | Keys ≥ fromKey |
subMap(from, to) | from inclusive, to exclusive |
descendingMap() | Reverse-order view |
pollFirstEntry() / pollLastEntry() | Remove and return smallest/largest entry |
11. Hashtable
Overview
Legacy class (Java 1.0). Works like HashMap but:
- Every method is
synchronized— thread-safe - No
nullkeys or values — throwsNullPointerException
HashMap vs Hashtable
| Feature | HashMap | Hashtable |
|---|---|---|
| Thread-safe | ❌ | ✅ |
| Null key | ✅ One | ❌ |
| Null values | ✅ | ❌ |
| Performance | Faster | Slower |
| Recommended | ✅ | ❌ (use ConcurrentHashMap) |
Hashtable is a legacy class. For thread-safe maps in new code, always use ConcurrentHashMap.12. Map Comparison Table
| Feature | HashMap | LinkedHashMap | TreeMap | Hashtable |
|---|---|---|---|---|
| Order | ❌ None | ✅ Insertion | ✅ Sorted by key | ❌ None |
| Thread-safe | ❌ | ❌ | ❌ | ✅ |
| Null key | ✅ One | ✅ One | ❌ | ❌ |
| Null values | ✅ | ✅ | ✅ | ❌ |
put/get | O(1) avg | O(1) avg | O(log n) | O(1) avg |
| Thread-safe alt | ConcurrentHashMap | — | synchronizedSortedMap | ConcurrentHashMap |
| When to use | Fast lookup | Fast lookup + order | Sorted keys, range queries | Avoid; use ConcurrentHashMap |
13. Comparable vs Comparator
Overview
When objects are stored in TreeSet/TreeMap or sorted with Collections.sort(), Java needs to know how to compare them. Two mechanisms exist:
Comparable— the class defines its own natural orderingComparator— an external class/lambda defines custom ordering
Comparable Natural Ordering
Interface
1// java.lang.Comparable2public interface Comparable<T> {3 int compareTo(T other);4}Return Value Contract
| Return | Meaning |
|---|---|
| Negative | this comes before other |
| Zero | Equal |
| Positive | this comes after other |
Code Example
1import java.util.*;2
3public class Student implements Comparable<Student> {4 String name;5 int age;6
7 Student(String name, int age) {8 this.name = name;9 this.age = age;10 }11
12 @Override13 public int compareTo(Student other) {14 return this.age - other.age; // natural order: ascending by age15 }16
17 @Override18 public String toString() { return name + "(" + age + ")"; }19
20 public static void main(String[] args) {21 List<Student> list = new ArrayList<>();22 list.add(new Student("Charlie", 22));23 list.add(new Student("Alice", 20));24 list.add(new Student("Bob", 21));25
26 Collections.sort(list); // uses compareTo()27 System.out.println(list); // [Alice(20), Bob(21), Charlie(22)]28
29 TreeSet<Student> set = new TreeSet<>(list); // also uses compareTo()30 System.out.println(set); // [Alice(20), Bob(21), Charlie(22)]31 }32}Comparator External Custom Ordering
Interface
1// java.util.Comparator (functional interface — can use lambda)2public interface Comparator<T> {3 int compare(T o1, T o2);4}Code Example Multiple Orderings
1import java.util.*;2
3public class ComparatorExample {4 record Student(String name, int age, double gpa) {}5
6 public static void main(String[] args) {7 List<Student> list = new ArrayList<>();8 list.add(new Student("Charlie", 22, 3.5));9 list.add(new Student("Alice", 20, 3.9));10 list.add(new Student("Bob", 21, 3.5));11 list.add(new Student("Diana", 20, 3.7));12
13 // Sort by name14 list.sort((s1, s2) -> s1.name().compareTo(s2.name()));15 System.out.println("By name: " + list);16
17 // Sort by age ascending18 list.sort((s1, s2) -> s1.age() - s2.age());19 System.out.println("By age: " + list);20
21 // Sort by GPA descending22 list.sort((s1, s2) -> Double.compare(s2.gpa(), s1.gpa()));23 System.out.println("By GPA desc: " + list);24
25 // Chained: by age, then by name26 list.sort(Comparator.comparingInt(Student::age)27 .thenComparing(Student::name));28 System.out.println("By age then name: " + list);29
30 // Use with TreeSet31 TreeSet<Student> sortedByName = new TreeSet<>(32 Comparator.comparing(Student::name));33 sortedByName.addAll(list);34 System.out.println("TreeSet by name: " + sortedByName);35 }36}Comparable vs Comparator Side-by-Side
| Feature | Comparable | Comparator |
|---|---|---|
| Package | java.lang | java.util |
| Method | compareTo(T other) | compare(T o1, T o2) |
| Defined in | The class itself | External class / lambda |
| Modifies original class? | ✅ Yes | ❌ No |
| Multiple orderings? | ❌ Only one | ✅ Unlimited |
| Functional interface? | ❌ | ✅ (Java 1.8) |
| Used by | Collections.sort(list) TreeSet TreeMap | Collections.sort(list, cmp) TreeSet(cmp) TreeMap(cmp) |
| When to use | One obvious natural order | Multiple criteria, or can't modify class |
Useful Comparator Factory Methods (Java 1.8+)
1Comparator.comparing(Student::name) // by field2Comparator.comparingInt(Student::age) // by int field3Comparator.comparingDouble(Student::gpa) // by double field4comparator.reversed() // reverse any comparator5Comparator.naturalOrder() // natural ascending6Comparator.reverseOrder() // natural descending7comparator1.thenComparing(comparator2) // chain comparatorsComparable = "I sort myself" (one natural order, modifies the class). Comparator = "Someone else sorts me" (multiple orders, no class modification needed).14. Full JCF Hierarchy Complete Picture
Complete Class Reference
| Class | Parent Interface(s) | Order | Thread-Safe | Null Key/Elem |
|---|---|---|---|---|
ArrayList | List | Insertion | ❌ | ✅ |
LinkedList | List, Deque | Insertion | ❌ | ✅ |
Vector | List | Insertion | ✅ | ✅ |
Stack | Vector | LIFO | ✅ | ✅ |
ArrayDeque | Deque | Insertion | ❌ | ❌ |
PriorityQueue | Queue | Priority (heap) | ❌ | ❌ |
HashSet | Set | None | ❌ | ✅ (one) |
LinkedHashSet | Set | Insertion | ❌ | ✅ (one) |
TreeSet | SortedSet | Sorted | ❌ | ❌ |
HashMap | Map | None | ❌ | ✅ (one key) |
LinkedHashMap | Map | Insertion/Access | ❌ | ✅ (one key) |
TreeMap | SortedMap | Sorted by key | ❌ | ❌ |
Hashtable | Map | None | ✅ | ❌ |
ConcurrentHashMap | Map | None | ✅ | ❌ |
15. Interview Notes
Q: Difference between HashSet, LinkedHashSet, TreeSet?
HashSet: no order; O(1); one null.LinkedHashSet: insertion order; O(1); one null.TreeSet: sorted; O(log n); no null.
Q: How does HashSet prevent duplicates? Backed by HashMap. On add(e), calls hashCode() to find bucket, then equals() to check for existing equal element. Duplicate → add() returns false.
Q: Why doesn't TreeSet allow null? Must compare elements to sort. Comparing null via compareTo() throws NullPointerException.
Q: HashMap vs Hashtable? HashMap: faster, not synchronized, one null key, multiple null values. Hashtable: all methods synchronized, no nulls, legacy class. Use ConcurrentHashMap instead of Hashtable.
Q: Why is ConcurrentHashMap better than synchronizedMap()? synchronizedMap uses one lock for the entire map — only one thread at a time. ConcurrentHashMap uses bucket-level locking — multiple threads can read/write different buckets simultaneously → far higher throughput.
Q: Comparable vs Comparator? Comparable = natural order, one per class, requires modifying the class, compareTo(). Comparator = custom/external, unlimited per class, no modification needed, compare(), functional interface.
Q: entrySet() vs keySet() for map iteration? entrySet() is preferred: gives both key and value in one object, one lookup per entry. keySet() + get(key) = two hash lookups per entry.
Q: What happens when you put() a duplicate key? New value overwrites old. put() returns the previous value (or null).
Q: Can HashMap have duplicate values? Yes — multiple keys can map to the same value. Duplicate keys: no — overwritten.
Q: TreeMap vs HashMap? HashMap: no order, O(1). TreeMap: sorted by key, O(log n), supports range queries (headMap, tailMap, subMap), no null keys.
16. Summary & Quick Revision
Revision Bullets
Set: no duplicates;add()returnsfalsefor duplicates; useshashCode()+equals().HashSet: no order; O(1) avg; backed byHashMap; one null.LinkedHashSet: insertion order; extendsHashSet.TreeSet: sorted; O(log n); Red-Black Tree; no null; extra:first(),last(),floor(),ceiling(),headSet(),tailSet().Map: key-value; separate fromCollection; no duplicate keys; duplicate values OK.HashMap: no order; O(1) avg; one null key; Java 8+ uses tree for long chains.LinkedHashMap: insertion order (or access order for LRU cache).TreeMap: sorted by key; O(log n); no null key; supportsheadMap(),tailMap(),subMap().Hashtable: legacy; fully synchronized; no nulls; useConcurrentHashMapinstead.Comparable: natural order; modifies class; one ordering;compareTo().Comparator: custom/external; no modification; multiple orderings;compare(); functional interface.entrySet()= most efficient map iteration (one lookup vs two forkeySet()+get()).
17. Practice Questions
Easy
- What is the main rule that defines a
Set? - Which
Setpreserves insertion order? Which sorts elements? - Can
TreeSetstore null? Why or why not? - What is the difference between
MapandCollection? - What does
map.put("A", 99)return if"A"already maps to50? - What is the difference between
ComparableandComparator? - Which
Mapimplementation keeps keys in sorted order?
Medium
- Write code to count word frequencies in a sentence using
HashMap. - Explain what happens if you override
equals()but NOThashCode()in a class stored in aHashSet. - Write a
Comparatorthat sortsStudentobjects by GPA descending, then by name ascending. - Explain the difference between
headMap(),tailMap(), andsubMap()inTreeMap. - How would you implement a simple LRU cache using
LinkedHashMap? - Write code to iterate a
HashMapefficiently usingentrySet(). - Write code demonstrating
putIfAbsent()andgetOrDefault().
Hard
- Explain
HashMap's internal structure in Java 8+. When does a linked list chain become a Red-Black Tree? - You cannot modify class
Employee. Write a single chainedComparatorthat sorts by department name, then salary descending, then name ascending. - Implement a program that finds the top 5 most frequent words in a paragraph using
HashMap+TreeMap(or sorted list). - Design a data structure with O(1)
insert, O(1)delete, and O(1)getRandom. (Hint: combineHashMap+ArrayList.) - Compare
ConcurrentHashMapvsCollections.synchronizedMap(new HashMap<>())in terms of lock granularity, null support, iteration safety, and throughput under concurrency. TreeSetusescompareTo()(orComparator) to determine equality — NOTequals(). Demonstrate a case where this causes surprising behavior when aComparatoris inconsistent withequals().
Iterable, Collection, iteration methods, Collection vs Collections
- Part 2 — Deque, ArrayDeque, List, ArrayList, LinkedList, Vector, Stack, ListIterator
- Part 3 — Set, Map, Comparable vs Comparator
Next: Java Streams API (Java 1.8) — stream(), filter(), map(), reduce(), collect(), flatMap(), lazy evaluation, parallel streams.Mastery check
How well can you recall this?
Finished this lesson?