top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Set in Java

Introduction 

Java provides a wide range of data structures to manipulate and store collections of elements. One such fundamental data structure is the Set. In this article, we will examine the Java notion of Set, its numerous operations, and how to carry them out using code examples. We will also explore the Set interface's particular actions and show you how to use them. So let's dive in and discover the power of Sets in Java. 

Overview 

A Set in Java is an unordered collection of unique elements. Unlike Lists or Arrays, Sets do not allow duplicate elements, ensuring that each element appears only once in the collection. This property makes Sets an ideal choice for scenarios where you need to eliminate duplicate entries or maintain a distinct set of elements. 

Creating Set Objects 

Any of the Set executions that are accessible, like HashSet, TreeSet, or LinkedHashSet, can be utilized to fabricate a Set object in Java. With code bits, pictures, and visuals, we should analyze every one of these implementations.

HashSet: The most often used implementation of the Set interface is HashSet in Java. It offers constant-time performance for fundamental operations like adding, deleting, or verifying for element existence but does not guarantee the order of the items. Here is an illustration of how to build a HashSet and add components to it: 

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
set.add("Orange");  

TreeSet in Java: The SortedSet interface is implemented by TreeSet, which offers items in sorted order. It maintains the elements in ascending order, which makes it suitable for scenarios where you require sorted data. Here's an example of creating a TreeSet and adding elements to it: 

java
Set<Integer> set = new TreeSet<>(); 
set.add(5); 
set.add(2); 
set.add(8);  

LinkedHashSet: Execution of the Set connection point that safeguards the addition request of components is LinkedHashSet.It combines the properties of both HashSet and LinkedList, providing uniqueness and maintaining the order of insertion. Here's an example of creating a LinkedHashSet and adding elements to it: 

java
Set<Character> set = new LinkedHashSet<>(); 
set.add('A'); 
set.add('B'); 
set.add('C');  

What Are the Operations You Can Perform on Set in Java? 

A Set object can be subjected to a variety of procedures after being formed. How about we look at the ordinary activities that the Java Set.

Adding Components: You might utilize the add() capability to add components to a Set. If the mentioned component isn't now present in the Set, it is added. Here is a delineation:

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
set.add("Orange");  

Accessing the Elements: You cannot access items by their index in sets since they don't save a specific request. To get to every component independently, you might go through the Set utilizing an iterator or reach out for a circle. Here is an outline:

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
set.add("Orange"); 
 
for (String element: set) { 
    System.out.println(element); 
}  

Removing Values: The remove() function might be utilized to erase a component from a Set. Assuming the mentioned component is available in the Set, it is eliminated. Here is a representation:

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
set.add("Orange"); 
 
set.remove("Banana");  

Iterating through the Set: As recently referenced, you can utilize an iterator or stretch out for a circle to explore the Set and connect with its parts. Here is a model:

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
set.add("Orange"); 
 
Iterator<String> iterator = set.iterator(); 
while (iterator.hasNext()) { 
    String element = iterator.next(); 
    System.out.println(element); 
} 

Operations on the Set Interface 

The Set interface provides several methods to perform operations on Sets. Let's explore some of the commonly used methods with code examples, screenshots, and images. 

  • Intersection

The retainAll() method allows you to perform the intersection operation on two Sets. Just the things that are likewise present in the given Set are kept as a component of the change to the ongoing Set. Here is a representation:

java
Set<String> set1 = new HashSet<>(); 
set1.add("Apple"); 
set1.add("Banana"); 
set1.add("Orange"); 
 
Set<String> set2 = new HashSet<>(); 
set2.add("Banana"); 
set2.add("Orange"); 
set2.add("Mango"); 
 
set1.retainAll(set2);  

  • Union

You may combine two Sets using the union operation by using the addAll() function. It adds each component from the picked Set to the one that is, as of now, there. 

java
Set<String> set1 = new HashSet<>(); 
set1.add("Apple"); 
set1.add("Banana"); 
set1.add("Orange"); 
 
Set<String> set2 = new HashSet<>(); 
set2.add("Banana"); 
set2.add("Orange"); 
set2.add("Mango"); 
 
set1.addAll(set2);  
  • Difference

The removeAll() technique permits you to play out the distinction procedure on two Sets. It eliminates every one of the components present in the predetermined Set from the ongoing Set. 

java 
Set<String> set1 = new HashSet<>(); 
set1.add("Apple"); 
set1.add("Banana"); 
set1.add("Orange"); 
 
Set<String> set2 = new HashSet<>(); 
set2.add("Banana"); 
set2.add("Orange"); 
set2.add("Mango"); 
 
set1.removeAll(set2);  

Performing Various Operations on SortedSet 

The Set interface is extended by the SortedSet interface, which offers more actions for sorted sets. Let's examine a few of these procedures and how to carry them out using screenshots, code samples, and visuals.

  • Adding Elements

The add() method is used to add elements to a SortedSet. It maintains the elements in sorted order based on their natural ordering or a custom Comparator. 

java
SortedSet<Integer> set = new TreeSet<>(); 
set.add(5); 
set.add(2); 
set.add(8);  
  • Accessing the Elements

You can access the elements in a SortedSet using iteration or specific methods such as first() and last(). 

java
SortedSet<Integer> set = new TreeSet<>(); 
set.add(5); 
set.add(2); 
set.add(8); 
 
int firstElement = set.first(); 
int lastElement = set.last();  
  • Removing the Values

The remove() method is utilized to eliminate a component from a SortedSet. It eliminates the predetermined component assuming it exists in the set.

java
SortedSet<Integer> set = new TreeSet<>(); 
set.add(5); 
set.add(2); 
set.add(8); 
 
set.remove(2);  
  • Iterating through the Set

You can traverse over a SortedSet using an Iterator or an improved for loop, just like you do with other Set implementations. 

java
SortedSet<Integer> set = new TreeSet<>(); 
set.add(5); 
set.add(2); 
set.add(8); 
 
Iterator<Integer> iterator = set.iterator(); 
while (iterator.hasNext()) { 
    int element = iterator.next(); 
    System.out.println(element); 
} 

Description 

Sets in Java are powerful tools for managing collections of unique elements. They provide methods for adding, accessing, removing, and iterating over elements. Sets also support set operations like intersection, union, and difference through the Set interface. The SortedSet interface extends the Set interface and adds sorting capabilities to the sets. 

Set Methods

The Set interface provides various methods to perform operations on Sets. Let's quickly go over a few of these techniques using screenshots, code samples, and visuals. 

add():

This method adds an element to the Set if it is not already present. 

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana");  

addAll(): 

This method adds all the elements from another collection to the Set. 

java
Set<String> set1 = new HashSet<>(); 
set1.add("Apple"); 
set1.add("Banana"); 
 
Set<String> set2 = new HashSet<>(); 
set2.addAll(set1);  

clear(): 

This method removes all the elements from the Set, making it empty. 

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
 
set.clear();  

contains(): 

This method checks whether the Set contains a specific element. 

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
 
boolean containsApple = set.contains("Apple");  

containsAll(): 

This method checks whether the Set contains all the elements from another collection. 

java
Set<String> set1 = new HashSet<>(); 
set1.add("Apple"); 
set1.add("Banana"); 
 
Set<String> set2 = new HashSet<>(); 
set2.add("Apple"); 
 
boolean containsAll = set1.containsAll(set2);  

hashCode(): 

This method returns the hash code value of the Set. 

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
 
int hashCode = set.hashCode();  

isEmpty(): 

This method checks whether the Set is empty. 

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
 
boolean isEmpty = set.isEmpty();  

iterator(): 

This method returns an iterator over the elements in the Set. Here's an example: 

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
 
Iterator<String> iterator = set.iterator(); 
while (iterator.hasNext()) { 
    String element = iterator.next(); 
    System.out.println(element); 
}  

remove(): 

This method removes a specific element from the Set if it exists. Here's an example: 

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
 
set.remove("Apple");  

removeAll(): 

This method removes all the elements from the Set that are present in another collection. Here's an example: 

java
Set<String> set1 = new HashSet<>(); 
set1.add("Apple"); 
set1.add("Banana"); 
 
Set<String> set2 = new HashSet<>(); 
set2.add("Apple"); 
 
set1.removeAll(set2);  

retainAll(): 

This strategy holds just the components from the Set that are available in another assortment, successfully playing out the crossing point activity. Here is a model:

java
Set<String> set1 = new HashSet<>(); 
set1.add("Apple"); 
set1.add("Banana"); 
 
Set<String> set2 = new HashSet<>(); 
set2.add("Apple"); 
 
set1.retainAll(set2);  

size(): 

This method returns the number of elements in the Set. Here's an example: 

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
 
int size = set.size();  

Conclusion 

Sets are robust data structures in Java that let you keep distinct components without duplication. In this post, we looked at the idea of sets, different Set implementations, and operations that may be used with sets. We covered creating Set objects, adding elements, accessing elements, removing values, iterating through Sets, and exploring specific operations for the Set and SortedSet interfaces. By understanding Sets and their operations, you can effectively manipulate and organize collections of elements in your Java programs. 

FAQs

1. What is a Set in Java, and how does it differ from other collection classes? 

A Set in Java is a collection that does not allow duplicate elements. Classes like HashSet, TreeSet, and LinkedHashSet are examples of those that implement it. Unlike a List and a Map, a Set does not keep a particular order for the components. It ensures that each element appears only once in the collection, making it the perfect solution for situations where uniqueness is a crucial necessity. 

2. In Java, how can I add elements to a Set? 

The add() function of the Set interface may be used to add elements to a Set. For example, you might add parts to a HashSet named "mySet" by utilizing mySet.add(element). The add() capability will return misleading, demonstrating that the component was not added, assuming the component is, as of now, present in the Set.

3. Could I, at any point, get parts out of a set in a specific request?

No, Sets do not ensure that the components will appear in a certain order, unlike List or Map. Utilize a SortedSet execution like TreeSet to hold components in arranged requests if you want to get to them in a predetermined request.

4. How might I decide if a component is essential for a Set?

The incorporates() strategy for the Set connection point in Java might be utilized to decide if a component is available in a Set. Assuming the component is situated in the Set, it returns valid; in any case, it gets back bogus.

5. Can I modify elements in a Set directly? 

No, the Set interface does not provide any methods to modify individual elements directly. To modify an element in a Set, you need to remove the old element and add the modified element as a separate operation. 

Leave a Reply

Your email address will not be published. Required fields are marked *