A Set is a collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2).
The Set interface is a member of the Java Collections Framework and extends the Collection interface.
SetSet guarantees that it will only store unique elements. If you try to add an element that already exists, the add operation will return false and the set will not be modified.List, a Set does not provide methods to access elements by a numerical index. You cannot ask for the "5th element" of a set.Set interface itself does not guarantee any order. Some implementations, like HashSet, are unordered, while others, like TreeSet (sorted) and LinkedHashSet (insertion-ordered), do maintain an order.Set MethodsThe Set interface inherits all its methods from the Collection interface, such as add(), remove(), size(), isEmpty(), contains(), and clear(). It doesn't add any new methods of its own.
The behavior of the add(E element) method is what makes Set unique. It only adds the element if it's not already present in the set.
Set ImplementationsSince Set is an interface, you need to use one of its implementing classes. The three most common implementations are:
HashSet: The most widely used Set implementation. It is backed by a hash table. It offers the best performance (O(1) for add, remove, and contains) but makes no guarantees concerning the order of iteration.TreeSet: This implementation stores elements in a sorted order (either natural ordering or by a Comparator provided at creation time). Its performance is slower (O(log n)) than HashSet.LinkedHashSet: This implementation maintains the insertion order of elements. It provides performance nearly as good as HashSet while also providing predictable iteration order.Here is an example of how to use a HashSet to store unique strings.
import java.util.HashSet; import java.util.Set;public class Main { public static void main(String[] args) { // Declare as a Set, instantiate as a HashSet Set<String> ingredients = new HashSet<>(); // Add elements ingredients.add("Flour"); ingredients.add("Sugar"); ingredients.add("Eggs"); // Try to add a duplicate element boolean wasAdded = ingredients.add("Sugar"); System.out.println("Was 'Sugar' added again? " + wasAdded); System.out.println("Set of ingredients: " + ingredients); // Check if an element exists if (ingredients.contains("Eggs")) { System.out.println("The set contains Eggs."); } // Loop through a set System.out.println("--- Looping through ingredients ---"); for (String ingredient : ingredients) { System.out.println(ingredient); } } }
Sets are powerful for performing mathematical set operations like:
set1.addAll(set2)set1.retainAll(set2)set1.removeAll(set2)