Set – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Thu, 13 Jul 2023 17:43:58 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg Set – Programmerbay https://programmerbay.com 32 32 HashSet Class in Java With Program Example https://programmerbay.com/hashset-class-in-java-with-program-example/ https://programmerbay.com/hashset-class-in-java-with-program-example/#respond Thu, 13 Jul 2023 17:43:58 +0000 https://programmerbay.com/?p=9366 Set interface doesn’t provide any additional method, as a result, implementation classes use only collection interface methods.
HashSet is an implementing class of Set interface and it represents Hash Table as its underlying data structure. It is a collection of unordered unique elements that don’t allow duplicates. It also doesn’t preserve insertion order as it uses hash code to store an element. Meaning, the elements are stored based on some hash values and can be retrieved in any order.

Screenshot from 2023 07 10 23 23 20

It uses several methods of Collection interface i.e. add(), remove(), contains(). The add() method returns false and doesn’t add an element if one tries to insert a duplicate element. The advantage of using HashSet, it makes searching faster.

It can store different types of objects and allows at most a single null value to hashSet.
It also implements the Serializable and Collneable interface.

Set is the best choice when the frequent search operation is required.

Syntax:

Set<String> set = new HashSet<String>();

Point to Remember :

  1. It doesn’t preserve insertion order
  2. It allows atmost single null value
  3. It can store various type of objects at the same time
  4. It uses hash table as its underlying data structure
  5. It is a best choice when frequent search operation is involved
  6. It doesn’t allow duplicate that makes it ideal for storing unique elements

 

Constructors of HashSet

There are 4 constructors in HashSet:

1) HashSet()

It is a default constructor that creates an empty Set with a default capacity of 16 elements and having default fill ratio 0.75.

HashSet<T> obj = new HashSet<>() :

Fill ratio/ Load Factor : It simply means after which ratio/ percentage, a new set should be created. For instance, if fill ratio is 0.75, then a new hashSet would be created after occupying 75% capacity of the set.

2) HashSet(int initialCapacity)

It creates an empty set with the provided initial capacity value with default fill ratio 0.75.

HashSet<T> h = new HashSet<>(int initialCapacity);

3) HashSet<T>(int initialCapacity, float loadFactor)

It creates an empty set with provided initial capacity and load factor.

HashSet<T> h = new HashSet<T>(int initialCapacity, float loadFactor);

4) HashSet<T>(Collection obj)

It creates a set with the collection elements passed in the constructor. It can be arrayList, linkedList or any other object that implements collection interface.

HashSet<T> h = new HashSet<T>(Collection obj);

Program to demonstrate creation of HashSet in Java

import java.util.*;

public class SetExample {
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<>() ;  // Creating set object
        set.add("Programmerbay");
        set.add("Example");
        set.add("Duplicate");
        set.add("Duplicate");
        System.out.println(set);
    }
}

Output:

[Example, Duplicate, Programmerbay]

 

How HashSet or HashMap works in Java?

HashSet internally uses the HashMap constructor to create an empty set with a default capacity of 16 and 0.75 load factor.
When the add() method is called, again put() method of HashMap is also invoked where the element that is being added acts as a key and a constant value (PRESENT) acts as a value. When one tries to add the same element then, we all know, what would happen when one tries to add an element with the same key in a map, it would override or replace the existing key-value pair. That is why HashSet doesn’t allow duplicate elements.

Further, lets see the working of HashMap.

HashMap also adheres HashTable Alogrithm Internally.

When a HashMap object is created, JVM creates Hash Table which is nothing but an array of nodes or buckets internally concerning the capacity of the Set or Map. These buckets act as a node that connects like a linked list.
When an element is added or put in the object, a corresponding hashcode or hash is generated using hashCode() method.

Based on the Modular operator it identifies the index and stores the data in that bucket (consisting array of nodes) residing on that position.
If two elements are having same hashcode, then it would not directly be stored in the same bucket, instead, the equal() method will be used to check whether the two elements are the same or not. If both are evaluated as different, then it would be stored in the same bucket otherwise, it will be replaced.

The situation of having the same hash of two elements is also known as Hashing collision, to deal with it, the equals() method is internally used by JVM.

Methods in HashSet

Method NameExplanation
add(Object)The method adds an element in a given set, returns false if one tries to add duplicate element
addAll(CollectionObj)It adds all the elements of the given collection in a given set
clear()It removes all elements from the given set
contains(Object)It checks whether the given object consists in a set or not, if it returns true if exist, otherwise false
containsAll(CollectionObj)It returns true, if all the elements of the given collection exist in the set, otherwise false
isEmpty()It checks whether a set is empty or not. it returns if empty, other false
iterator()It provides iterator object to iterate through set
remove(Object)It removes the given object from the set, if present
retainAll(CollectionObj)It retains elements of the collection provided in the method, and removed all other elements in the set that don't match the elements of collection object
size()It returns number of elements present in a set
spliterator()it returns spliterator object to iterate through set
toArray()It converts given set and returns array
removeAll(CollectionObj)It removes all the elements consisting in the collection object

]]>
https://programmerbay.com/hashset-class-in-java-with-program-example/feed/ 0
Set Interface In Java With Program Example https://programmerbay.com/set-interface-in-java-with-program-example/ https://programmerbay.com/set-interface-in-java-with-program-example/#respond Mon, 10 Jul 2023 17:57:29 +0000 https://programmerbay.com/?p=9365 Set is a child interface of the Collection interface that represents an unordered collection where each element is unique and cannot be repeated. It only consists of methods inherited from its parent interface and doesn’t allow duplicate elements. Further, if someone tries to add a duplicate via add() method, then it would return false, signifying the given element is not able to get added. It is part of java.util package.

Screenshot from 2023 07 10 23 23 20
It provides several essential methods that can be used to store, manipulate and search elements in a given set. It depicts a mathematical set and provides its abstraction.

There are various methods which implement the Set interface, including HashSet, LinkedHashSet and TreeSet.
SortedSet and NavigableSet interfaces further extend Set Interface that provides additional behaviour and different implementation to the existing method. NavigableSet is a child interface of SortedSet that provides navigational methods to navigate through a Set. It has a child class named TreeSet which is an implementation of the self-balancing tree.

How to declare and initialise a Set Object in Java?

Set interface provides specification only, in order to create its object, one requires its implementing class i.e HashSet,TreeSet, in order to create an object. With the help of Generics, we can specify the type of object that a Set Collection can store.

Set<T> set = new HashSet<T> ();

Point to Remember:

  • It doesn’t preserve order of inserted elements
  • It allows at most single null element
  •  It doesn’t allow duplicate elements
  • It can have elements of different types

Methods of Set Interface

The methods supported by Set Interface are listed below :

Method NameExplanation
add(Object)The method adds an element in a given set, returns false if one tries to add duplicate element
addAll(CollectionObj)It adds all the elements of the given collection in a given set
clear()It removes all elements from the given set
contains(Object)It checks whether the given object consists in a set or not, if it returns true if exist, otherwise false
containsAll(CollectionObj)It returns true, if all the elements of the given collection exist in the set, otherwise false
isEmpty()It checks whether a set is empty or not. it returns if empty, other false
iterator()It provides iterator object to iterate through set
remove(Object)It removes the given object from the set, if present
retainAll(CollectionObj)It retains elements of the collection provided in the method, and removed all other elements in the set that don't match the elements of collection object
size()It returns number of elements present in a set
spliterator()it returns spliterator object to iterate through set
toArray()It converts given set and returns array
removeAll(CollectionObj)It removes all the elements consisting in the collection object

Java Program to demonstrate working of Set interface

Program:

import java.util.HashSet;
import java.util.Set;

public class SetExample {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>() ;  // Creating set object
        set.add("The");
        set.add("Programmerbay");
        set.add("Code");
        set.add("Example");

        System.out.println("Printing Added element :: "+set);
        set.add("Code");  //  Adding duplicate element
        System.out.println("Duplicate element not present :: "+set);
        set.remove("Example");  //  Removing duplicate element
        System.out.println("Removing 'Example' element :: "+set);


    }
}

Output:

Printing Added element :: [The, Example, Code, Programmerbay]
Duplicate element not present :: [The, Example, Code, Programmerbay]
Removing 'Example' element :: [The, Code, Programmerbay]

Basic Operations Supported by Set and Its implementing Classes

1) Add Elements :

Set interface specifies add(object) and addAll(CollectionObj) to add elements to a set. It doesn’t preserves insertion order of inserted elements. In contrast, it uses hashing mechanism to store elements where a hash of an element is generated and stored in a hash table. As mentioned before, it doesn’t allow duplicates, but accepts atmost single null value.

Java program to add single element and multiple elements in a Set using add() and addAll() method

Program:

public class SetExample {
public static void main(String[] args) {
Set<String> set = new HashSet<>() ; // Creating set object
Collection<String> collection = List.of( "Another","Collection","inserted");

set.add("Programmerbay");

System.out.println("Single Added element :: "+set);

set.addAll(collection); // Adding collection elements, but order will not be preserved

System.out.println("Collection added to set :: "+ set);

}
}

Output:

Single Added element :: [Programmerbay]
Collection added to set :: [inserted, Collection, Programmerbay, Another]

2) Remove Elements:

Set interface offers three methods for this, however, all have different use cases.
1) remove() -> It removes a single element
2) removeAll() -> It accepts a collection object and removes all elements that match the targeted set.
3) retainAll () -> Opposite to removeAll(), it accepts a collection object and persists only those elements that match with the provided collection, other elements that are present in the targeted set get removed.

Java program to remove single element and multiple elements in a Set using remove() and removeAll() method

Program:

public class SetExample {
public static void main(String[] args) {
Set<String> set = new HashSet<>() ; // Creating set object
Collection<String> retainObjs = List.of("Programmerbay","Code");
Collection<String> removeAllObj = List.of("Remove1","Remove2");

// Adding random elements
set.add("Remove Me");
set.add("Remove1");
set.add("Remove2");
set.add("Programmerbay");
set.add("Example");
set.add("The");
set.add("Code");


System.out.println("Elements :: "+set);

// removing 'remove Me' from the list
set.remove("Remove Me");

System.out.println("After single remove :: "+set);

set.removeAll(removeAllObj); // remove1 and remove2 stored in removeAllObj would remove elements in set

System.out.println("after removeAll() :: "+ set);

set.retainAll(retainObjs); // Programmerbay and Code stored in reainAllObj would store elements and remove others from the set

System.out.println("after retainAll() :: "+ set);

}
}

Output:

Elements :: [The, Remove1, Remove2, Remove Me, Example, Code, Programmerbay]
After single remove :: [The, Remove1, Remove2, Example, Code, Programmerbay]
after removeAll() :: [The, Example, Code, Programmerbay]
after retainAll() :: [Code, Programmerbay]

4) Iterate over Elements:

There are multiple ways to iterate over elements of a set. These are the following:
1) using iterator
2) Using forEach()
3) Using Java 8 Stream

Java program to iterate over elements of a set.

program:

public class SetExample {
public static void main(String[] args) {
Set<String> set = new HashSet<>() ; // Creating set object

// Adding random elements
set.add("Remove Me");
set.add("Remove1");
set.add("Remove2");
set.add("Programmerbay");
set.add("Example");
set.add("The");
set.add("Code");

Iterator iterator = set.iterator(); // fetching iterator object of the set

System.out.println("Iterating through iterator object :: ");
while (iterator.hasNext()){
System.out.println(iterator.next());
}


// using for each
System.out.println("Iterating through for each loop :: ");

for (String element:
set) {
System.out.println( element);
}

// using Java 8 Stream
System.out.println("Iterating through using java 8 stream :: ");

set.stream().forEach(e -> System.out.println("element :: "+ e));

}
}

Output:

Iterating through iterator object ::
The
Remove1
Remove2
Remove Me
Example
Code
Programmerbay
Iterating through for each loop ::
The
Remove1
Remove2
Remove Me
Example
Code
Programmerbay
Iterating through using java 8 stream ::
element :: The
element :: Remove1
element :: Remove2
element :: Remove Me
element :: Example
element :: Code
element :: Programmerbay


Implementing Classes of Set Interface

HashSet class : Hashset class is a implementing class of Set interface that uses hash table as its underlying data structure. It doesn’t preserves insertion order,meaning, the order in which elements are inserted may differ as it hash code to insert data. It accepts null values.

public class SetExample {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>() ;  // Creating set object
        set.add("Programmerbay");
        set.add("Example");
        System.out.println(set);
    }
}

Output:

[Example, Programmerbay]

LinkedHashSet class : It also implements Set interface and exhibits the behavior of doubly linked list. Unlike HashSet, it preserves insertion order.

public class SetExample {
    public static void main(String[] args) {
        Set<String> set = new LinkedHashSet<>() ;  // Creating set object
        set.add("Programmerbay");
        set.add("Example");
        System.out.println(set);
    }
}

Output:

[Programmerbay, Example]

 

TreeSet class : It is a implementation class of SortedSet interface. It resembles tree data structure to store and manage data. It stores data in natural sorting order.

public class SetExample {
    public static void main(String[] args) {
        Set<String> set = new TreeSet<>() ;  // Creating set object
        set.add("Programmerbay");
        set.add("Example");
        System.out.println(set);
    }
}

Output:

[Example, Programmerbay]

 

 

 

]]>
https://programmerbay.com/set-interface-in-java-with-program-example/feed/ 0