DEV Community

Neelakandan R
Neelakandan R

Posted on

3 3 3 3 3

Set in Java

Set in Java

In Java, the set is an interface that belongs to java.util package. The Set interface extends the Collection interface. An unordered collection or list in which duplicates are not allowed is referred to as a Collection interface. The set interface is used to create the mathematical set. The set interface use collection interface's methods to avoid the insertion of the same elements. SortedSet and NavigableSet are two interfaces that extend the set implementation.

import java.util.*;     
    public class SetExample1{     
        public static void main(String[] args)     
        {     
            // creating LinkedHashSet using the Set    
            Set<String> data = new LinkedHashSet<String>();     
            data.add("JavaTpoint");     
            data.add("Set");     
            data.add("Example");     
            data.add("Set");     
            System.out.println(data);     
        }     
    }     
Enter fullscreen mode Exit fullscreen mode

Set Methods

There are several methods available in the Set interface which we can use to perform a certain operation on our sets. These methods are as follows:

1) Set.add() Method

The add() method insert a new value to the set. The method returns true and false depending on the presence of the insertion element. It returns false if the element is already present in the set and returns true if it is not present in the set.

data.add(31);  
Enter fullscreen mode Exit fullscreen mode

** 2) Set.addAll() Method**

The addAll() method appends all the elements of the specified collection to the set.

Syntax:

boolean addAll(Collection data)
Enter fullscreen mode Exit fullscreen mode
import java.io.*;     
    import java.util.*;    
    class SetExample4 {     
        public static void main(String args[])     
        {     
            Set<Integer> data = new LinkedHashSet<Integer>();     
            data.add(31);     
            data.add(21);     
            data.add(41);     
            System.out.println("Set: " + data);    
            ArrayList<Integer> newData = new ArrayList<Integer>();     
            newData.add(91);     
            newData.add(71);     
            newData.add(81);    
            data.addAll(newData);     
            System.out.println("Set: " + data);         
        }     
    }     

Enter fullscreen mode Exit fullscreen mode

3) Set.clear() Method

The method removes all the elements from the set. It doesn't delete the reference of the set. It only deletes the elements of the set.

Syntax:

void clear()
Enter fullscreen mode Exit fullscreen mode
 import java.io.*;   
    import java.util.*;   
    public class SetExample5 {   
        public static void main(String args[])   
        {   
            Set<Integer> data = new LinkedHashSet<Integer>();   

            data.add(31);   
            data.add(21);   
            data.add(41);   
            System.out.println("Set: " + data);  

            data.clear();   
            System.out.println("The final set: " + data);   
        }   
    }  

Enter fullscreen mode Exit fullscreen mode

4) Set.contains() Method

The contains() method is used to know the presence of an element in the set. Its return value is true or false depending on the presence of the element.

Syntax:

boolean contains(Object element)  
Enter fullscreen mode Exit fullscreen mode

5) Set.containsAll() Method

The method is used to check whether all the elements of the collection are available in the existing set or not. It returns true if all the elements of the collection are present in the set and returns false even if one of the elements is missing in the existing set.

Syntax:

public boolean containsAll(Collection data) 

    import java.io.*;   
    import java.util.*;   
    class SetExample6 {   
        public static void main(String args[])   
        {   
            Set<Integer> data = new LinkedHashSet<Integer>();   
            data.add(31);   
            data.add(21);   
            data.add(41);   
            data.add(51);   
            data.add(11);   
            data.add(81);   
            System.out.println("Set: " + data);  
            System.out.println("Does the Set contains '91'?" + data.contains(91));   
            System.out.println("Does the Set contains 'javaTpoint'? " + data.contains("4"));  
            System.out.println("Does the Set contains '51'? " + data.contains(51));  
        }   
    }   
Enter fullscreen mode Exit fullscreen mode

6) Set.hashCode() Method

The method is used to derive the hash code value for the current instance of the set. It returns hash code value of integer type.

Syntax:

public int hashCode()
Enter fullscreen mode Exit fullscreen mode

7) Set.isEmpty() Method

The isEmpty() method is used to identify the emptiness of the set . It returns true if the set is empty and returns false if the set is not empty.

Syntax:

boolean isEmpty()  
Enter fullscreen mode Exit fullscreen mode

8) Set.iterator() Method

The iterator() method is used to find the iterator of the set. The iterator is used to get the element one by one.

Syntax:

Iterator iterate_value = set1.iterator();  
Enter fullscreen mode Exit fullscreen mode

9) Set.remove() Method

The method is used to remove a specified element from the Set. Its return value depends on the availability of the element. It returns true if the element is available in the set and returns false if it is unavailable in the set.

Syntax:

boolean remove(Object O)  
Enter fullscreen mode Exit fullscreen mode

10) Set.removeAll() Method

The method removes all the elements of the existing set from the specified collection.

Syntax:

public boolean removeAll(Collection data)  
Enter fullscreen mode Exit fullscreen mode

11) Set.size() Method

The method returns the size of the set.

Syntax:

int size()  
Enter fullscreen mode Exit fullscreen mode

Common Set Implementations

HashSet: HashSet is one of the most commonly used Set implementations in Java. It uses a hash table for storage and provides constant-time performance for basic operations like add, remove, and contains. However, it does not guarantee the order of elements.

TreeSet: TreeSet is an implementation of the Set interface that uses a Red-Black tree for storage. It maintains elements in sorted order that makes it suitable for scenarios where elements need to be accessed in a sorted manner.

*LinkedHashSet: *LinkedHashSet is a hybrid data structure that combines a hash table with a linked list. It maintains a predictable iteration order that is the order in which elements were inserted into the set.

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

Top comments (0)

Image of Stellar post

How a Hackathon Win Led to My Startup Getting Funded

In this episode, you'll see:

  • The hackathon wins that sparked the journey.
  • The moment José and Joseph decided to go all-in.
  • Building a working prototype on Stellar.
  • Using the PassKeys feature of Soroban.
  • Getting funded via the Stellar Community Fund.

Watch the video

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay