What is the Set interface?
- The Set interface in Java is your go-to when you need a collection that stores unique elements only. No duplicates, no index-based access.
-Set extends the Collection interface and lives in java.util. Its defining contract: it will never contain duplicate elements.
-Internally, "duplicate" is determined by equals() and hashCode() — so you must override both when using custom objects.
1.HashSet:
Use HashSet when you only care about uniqueness and O(1) average-case performance, and don't need a predictable iteration order.
O(1) avg -Backed by a HashMap. Fastest for add/remove/contains. No ordering guarantee whatsoever.
Example:
Set<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Mango");
fruits.add("Apple"); // duplicate — silently ignored System.out.println(fruits.size()); // 2 System.out.println(fruits.contains("Mango")); // true
2.LinkedHashSet — insertion order preserved :
When you need deduplication but iteration must reflect the order elements were added, LinkedHashSet is the answer.
O(1) avg
-HashSet + doubly-linked list. Preserves insertion order. Slightly more memory than HashSet.
Example:
Set<String> steps = new LinkedHashSet<>();
steps.add("Login");
steps.add("Dashboard");
steps.add("Login"); // duplicate dropped
steps.add("Logout");
steps.forEach(System.out::println); // Login → Dashboard → Logout
3.TreeSet — sorted order, always:
TreeSet keeps elements in ascending natural order (or your custom Comparator).
O(log n)
-Backed by a Red-Black tree. Elements stored in sorted (natural or custom Comparator) order.
Example:
Set<Integer> scores = new TreeSet<>();
scores.add(42);
scores.add(7);
scores.add(19);
System.out.println(scores); // [7, 19, 42] — always sorted // NavigableSet methods (cast required)
TreeSet<Integer> nav = (TreeSet<Integer>) scores; System.out.println(nav.floor(20)); // 19 System.out.println(nav.ceiling(20)); // 42
Difference between HashSet and LinkedHashSet and TreeSet:

Top comments (0)