Learn about the Set interface and its implementations in Java, including HashSet, LinkedHashSet, and TreeSet.
Here are some examples demonstrating key Set concepts:
import java.util.HashSet; import java.util.Set; public class SetExample { public static void main(String[] args) { // Creating a new HashSet Set<String> fruits = new HashSet<>(); // Adding elements to the Set fruits.add("Apple"); fruits.add("Banana"); fruits.add("Orange"); fruits.add("Apple"); // Duplicate - will not be added // Iterating over elements System.out.println("Fruits in the set:"); for (String fruit : fruits) { System.out.println(fruit); } // Checking if an element exists System.out.println("Contains Apple? " + fruits.contains("Apple")); // Removing an element fruits.remove("Banana"); // Size of the Set System.out.println("Number of fruits: " + fruits.size()); } }
import java.util.HashSet; import java.util.Set; public class SetOperationsExample { public static void main(String[] args) { // First set Set<Integer> set1 = new HashSet<>(); set1.add(1); set1.add(2); set1.add(3); set1.add(4); // Second set Set<Integer> set2 = new HashSet<>(); set2.add(3); set2.add(4); set2.add(5); set2.add(6); // Union (create a new set with all elements) Set<Integer> union = new HashSet<>(set1); union.addAll(set2); System.out.println("Union: " + union); // Intersection (elements present in both sets) 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); } }