Set in Java
a Set is a collection that contains no duplicate elements. The Set interface is a part of the Java Collections Framework and provides several implementations such as HashSet, TreeSet, and LinkedHashSet.
Get Wealthy Man’s stories in your inbox
Join Medium for free to get updates from this writer.
In this blog, we’ll explore what a Set is, how to create one in Java, and how to manipulate its elements using the add(), remove(), and contains() methods.
Creating a Set in Java
To create a Set in Java, you can use one of the implementations of the Set interface provided by the Java Collections Framework, such as HashSet, TreeSet, or LinkedHashSet. Here’s an example of how to create a HashSet:
Set<String> mySet = new HashSet<>();In this example, we create a Set that stores String elements using the HashSet implementation.
Adding Elements to a Set
To add an element to a Set, you can use the add() method. Here's an example:
mySet.add("apple");
mySet.add("banana");
mySet.add("orange");In this example, we add three elements to the Set.
Retrieving Elements from a Set
To retrieve an element from a Set, you can use the contains() method. Here's an example:
if (mySet.contains("banana")) {
System.out.println("The Set contains banana");
} else {
System.out.println("The Set does not contain banana");
}In this example, we check if the Set contains the element “banana” using the contains() method.
Removing Elements from a Set
To remove an element from a Set, you can use the remove() method. Here's an example:
mySet.remove("apple");In this example, we remove the element “apple” from the Set using the remove() method.
Iterating over a Set
You can also iterate over a Set in Java using a for-each loop. Here’s an example:
for (String element : mySet) {
System.out.println(element);
}In this example, we iterate over the Set using a for-each loop and print each element.
Conclusion
In this blog, we’ve explored what a Set is in Java, how to create one, and how to add, retrieve, and remove elements from a Set. By understanding how to work with Sets in Java, you’ll be better equipped to build applications that can handle collections of unique elements effectively.
Thanks for reading.






