Java Set Interface
Collections that contain only unique elements
🎯 What is a Java Set?
Set is a collection interface that ensures all elements are unique, automatically preventing duplicates and providing fast membership testing for data integrity.
// Creating and using a Set
import java.util.*;
Set<String> colors = new HashSet<>();
colors.add("Red");
colors.add("Blue");
colors.add("Red"); // Duplicate - won't be added
System.out.println(colors); // Only unique elements
System.out.println("Size: " + colors.size());
Output:
[Red, Blue]
Size: 2
Set Key Features
Unique Elements
No duplicate values allowed
set.add("item");
set.add("item"); // Ignored
Fast Lookup
Quick contains() operations
boolean exists = set.contains("item");
Set Operations
Union, intersection, difference
set1.retainAll(set2); // Intersection
No Indexing
Elements not accessible by index
// set.get(0); // Not available
🔹 Set Implementations
Different types of Set implementations:
🔸 HashSet vs LinkedHashSet vs TreeSet
- HashSet: Fastest, no ordering guarantee
- LinkedHashSet: Maintains insertion order
- TreeSet: Keeps elements sorted
import java.util.*;
public class SetTypes {
public static void main(String[] args) {
// HashSet - fastest, no order
Set<String> hashSet = new HashSet<>();
hashSet.add("Banana");
hashSet.add("Apple");
hashSet.add("Cherry");
System.out.println("HashSet: " + hashSet);
// LinkedHashSet - maintains insertion order
Set<String> linkedSet = new LinkedHashSet<>();
linkedSet.add("Banana");
linkedSet.add("Apple");
linkedSet.add("Cherry");
System.out.println("LinkedHashSet: " + linkedSet);
// TreeSet - sorted order
Set<String> treeSet = new TreeSet<>();
treeSet.add("Banana");
treeSet.add("Apple");
treeSet.add("Cherry");
System.out.println("TreeSet: " + treeSet);
}
}
Output:
HashSet: [Apple, Cherry, Banana]
LinkedHashSet: [Banana, Apple, Cherry]
TreeSet: [Apple, Banana, Cherry]
🔹 Common Set Operations
Essential Set methods and operations:
import java.util.*;
public class SetOperations {
public static void main(String[] args) {
Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
Set<Integer> set2 = new HashSet<>(Arrays.asList(4, 5, 6, 7, 8));
System.out.println("Set1: " + set1);
System.out.println("Set2: " + set2);
// Basic operations
System.out.println("Set1 contains 3: " + set1.contains(3));
System.out.println("Set1 size: " + set1.size());
System.out.println("Set1 is empty: " + set1.isEmpty());
// Union (all elements from both sets)
Set<Integer> union = new HashSet<>(set1);
union.addAll(set2);
System.out.println("Union: " + union);
// Intersection (common elements)
Set<Integer> intersection = new HashSet<>(set1);
intersection.retainAll(set2);
System.out.println("Intersection: " + intersection);
// Difference (elements in set1 but not in set2)
Set<Integer> difference = new HashSet<>(set1);
difference.removeAll(set2);
System.out.println("Difference (set1 - set2): " + difference);
// Subset check
Set<Integer> subset = new HashSet<>(Arrays.asList(1, 2));
System.out.println("Is {1,2} subset of set1: " + set1.containsAll(subset));
}
}
Output:
Set1: [1, 2, 3, 4, 5]
Set2: [4, 5, 6, 7, 8]
Set1 contains 3: true
Set1 size: 5
Set1 is empty: false
Union: [1, 2, 3, 4, 5, 6, 7, 8]
Intersection: [4, 5]
Difference (set1 - set2): [1, 2, 3]
Is {1,2} subset of set1: true
🔹 Iterating Through Sets
Different ways to loop through Set elements:
Set<String> fruits = new HashSet<>(Arrays.asList("Apple", "Banana", "Orange"));
// 1. Enhanced for loop (most common)
System.out.println("Enhanced for loop:");
for (String fruit : fruits) {
System.out.println(fruit);
}
// 2. Iterator
System.out.println("\nUsing Iterator:");
Iterator<String> iterator = fruits.iterator();
while (iterator.hasNext()) {
String fruit = iterator.next();
System.out.println(fruit);
// Can safely remove during iteration
// iterator.remove(); // if needed
}
// 3. Stream API (Java 8+)
System.out.println("\nUsing Stream:");
fruits.stream()
.sorted() // Sort for consistent output
.forEach(System.out::println);
// 4. Convert to array first
System.out.println("\nUsing array:");
String[] fruitArray = fruits.toArray(new String[0]);
for (String fruit : fruitArray) {
System.out.println(fruit);
}
🔹 Practical Set Examples
Real-world use cases for Sets:
import java.util.*;
public class SetExamples {
public static void main(String[] args) {
// Example 1: Remove duplicates from a list
List<String> listWithDuplicates = Arrays.asList("A", "B", "A", "C", "B", "D");
Set<String> uniqueElements = new HashSet<>(listWithDuplicates);
System.out.println("Original: " + listWithDuplicates);
System.out.println("Unique: " + uniqueElements);
// Example 2: Check for common interests
Set<String> person1Interests = new HashSet<>(Arrays.asList("Reading", "Gaming", "Cooking"));
Set<String> person2Interests = new HashSet<>(Arrays.asList("Gaming", "Movies", "Cooking"));
Set<String> commonInterests = new HashSet<>(person1Interests);
commonInterests.retainAll(person2Interests);
System.out.println("Common interests: " + commonInterests);
// Example 3: Validate unique usernames
Set<String> registeredUsers = new HashSet<>();
String[] newUsers = {"john123", "mary456", "john123", "bob789"};
for (String username : newUsers) {
if (registeredUsers.add(username)) {
System.out.println("User " + username + " registered successfully");
} else {
System.out.println("Username " + username + " already exists");
}
}
System.out.println("Total registered users: " + registeredUsers.size());
}
}
Output:
Original: [A, B, A, C, B, D]
Unique: [A, B, C, D]
Common interests: [Gaming, Cooking]
User john123 registered successfully
User mary456 registered successfully
Username john123 already exists
User bob789 registered successfully
Total registered users: 3