Browse by Domains

Introduction to Hashset in Java

In this article, we’ll plunge into HashSet Java. It’s perhaps the most mainstream Set executions just as a fundamental piece of the Java Collections Framework. 

HashSet is one of the crucial information structures in the Java Collections API. We should review the main parts of this execution: 

  • It stores extraordinary components and grants nulls 
  • It’s sponsored by a HashMap 
  • It doesn’t keep up inclusion request 
  • It’s not string safe 

Note that this interior HashMap gets introduced when an occurrence of the HashSet is made: 

public HashSet() { 

map = new HashMap<>(); 

} 


In the event that you need to go further into how the HashMap functions, you can peruse the article zeroed in on it here. 

java

The API 

In this segment, we will survey most usually utilized techniques and view some straightforward models. 

1. add()

The add() technique can be utilized for adding components to a set. The technique contract expresses that a component will be added just when it is absent in a set. On the off chance that a component was added, the technique returns valid, something else – bogus. 

We can add a component to a HashSet like: 

@Test 

public void whenAddingElement_shouldAddElement() { 

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

assertTrue(hashset.add("String Added")); 

} 

From an execution point of view, the add strategy is a critical one. Execution subtleties delineate how the HashSet functions inside and use the HashMap’s put technique: 

public boolean add(E e) { 

return map.put(e, PRESENT) == invalid; 

} 

freestar 

The guide variable is a reference to the inner, backing HashMap: 

private transient HashMap<E, Object> map; 

It’d be a smart thought to get comfortable with the hashcode first to get a nitty gritty comprehension of how the components are coordinated in hash-based information structures. 

Summing up: 

A HashMap is a variety of cans with a default limit of 16 components – each can compares to an alternate hashcode esteem 

In the event that different items have the equivalent hashcode esteem, they get put away in a solitary pail.

On the off-chance that the heap factor is reached, another exhibit gets made double the size of the past the whole gang components get repeated and rearranged among new comparing pails 

To recover a worth, we hash a key, mod it, and afterward go to a comparing can and search through the likely connected rundown in the event of there’s in excess of a one articleJava HashSet class is utilized to make an assortment that utilizes a hash table for capacity. It acquires the AbstractSet class and carries out Set interface

The significant focuses about Java HashSet class are:

  • HashSet stores the components by utilizing a system called hashing. 
  • HashSet contains extraordinary components as it were. 
  • HashSet permits invalid worth. 
  • HashSet class is non synchronized. 
  • HashSet doesn’t keep up the inclusion request. Here, components are embedded based on their hashcode. 
  • HashSet is the best methodology for search tasks. 
  • The underlying default limit of HashSet is 16, and the heap factor is 0.75.

Contrast among List and Set 

A rundown can contain copy components while Set contains one of a kind components in particular. 

Pecking order of HashSet class 

The HashSet class expands AbstractSet class which executes Set interface. The Set interface acquires Collection and Iterable interfaces in progressive request.

HashSet class affirmation 

We should see the presentation for java.util.HashSet class.

public class HashSet<E> expands AbstractSet<E> carries out Set<E>, Cloneable, Serializable

Constructors of Java HashSet class

1) HashSet(): It is utilized to build a default HashSet. 

2) HashSet(int capacity): It is utilized to instate the limit of the hash set to the given number worth limit. The limit develops consequently as components are added to the HashSet. 

3) HashSet(int limit, glide loadFactor): It is utilized to introduce the limit of the hash set to the given whole number worth limit and the predetermined burden factor. 

4) HashSet(Collection<? stretches out E> c): It is utilized to instate the hash set by utilizing the components of the assortment c. 

Strategies for Java HashSet class

Different strategies for Java HashSet class are as per the following: 

SN                  Method and TypeDescription
1) boolean            add(E e)It is utilized to add the predefined component to this set in the event that it isn’t now present.
2) void  clear()It is utilized to the entirety of the components from the set.
3) object  clone()It is utilized to return a shallow duplicate of this HashSet occasion: the actual components are not cloned
4) boolean  contains(Object o)It is utilized to return valid if this set contains the predetermined component.
5) booleanisEmpty()It is utilized to return valid if this set contains no components. 
6) Iterator<E>iterator()It is utilized to return an iterator over the components in this set. 
7) booleanremove(Object o)It is utilized to eliminate the predefined component from this set on the off chance that it is available.
8) intsize()It is utilized to return the quantity of components in the set. 
9) Spliterator<E>  spliterator()It is utilized to make a late-restricting and fizzle quick Spliterator over the components in the set

Java HashSet Example 

What about we see an essential outline of HashSet. Notice, the parts rehash in an unordered arrangement.

import java.util.*; 

class HashSet1{ 

public static void main(String args[]){ 
/Creating HashSet and adding components 

HashSet<String> set=new HashSet(); 

 set.add("One"); 

set.add("Two"); 

 set.add("Three"); 

set.add("Four"); 

set.add("Five"); 
Iterator<String> i=set.iterator(); 

while(i.hasNext()) 

{ 

System.out.println(i.next()); 

} 

} 

} 

Output:

Five 

One 

Four 

Two 

Three 

Java HashSet model ignoring duplicate parts 

In this model, we see that HashSet doesn’t allow duplicate parts:

import java.util.*; 

class HashSet2{ 

public static void main(String args[]){ 

/Creating HashSet and adding components 

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

set.add("Ravi"); 

set.add("Vijay"); 

set.add("Ravi"); 

set.add("Ajay"); 

/Traversing components 

Iterator<String> itr=set.iterator(); 

 while(itr.hasNext()){ 

System.out.println(itr.next()); 

 } 

} 

} 

Output:

Ajay 

Vijay 

Ravi

Java HashSet guide to eliminate components 

Here, we see various approaches to eliminate a component:

import java.util.*; 

class HashSet3{ 

public static void main(String args[]){ 

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

set.add("Ravi"); 

set.add("Vijay"); 

set.add("Arun"); 

set.add("Sumit"); 

System.out.println("An beginning rundown of components: "+set); 

/Removing explicit component from HashSet 

set.remove("Ravi"); 

System.out.println("After conjuring remove(object) technique: "+set); 

HashSet<String> set1=new HashSet<String>(); 

set1.add("Ajay"); 

set1.add("Gaurav"); 

set.addAll(set1); 

System.out.println("Updated List: "+set); 

/Removing every one of the new components from HashSet 

set.removeAll(set1); 

System.out.println("After summoning removeAll() technique: "+set); 

/Removing components based on indicated condition 

set.removeIf(str->str.contains("Vijay")); 

System.out.println("After conjuring removeIf() strategy: "+set); 

/Removing every one of the components accessible in the set 

set.clear(); 

System.out.println("After conjuring clear() strategy: "+set); 

} 

} 


An underlying rundown of components: [Vijay, Ravi, Arun, Sumit] 

Subsequent to summoning remove(object) technique: [Vijay, Arun, Sumit] 

Refreshed List: [Vijay, Arun, Gaurav, Sumit, Ajay] 

Subsequent to summoning removeAll() technique: [Vijay, Arun, Sumit] 

Subsequent to summoning removeIf() technique: [Arun, Sumit] 

Subsequent to summoning clear() technique: [] 

Java HashSet from another Collection 

import java.util.*; 

class HashSet4{ 

public static void main(String args[]){ 

ArrayList<String> list=new ArrayList<String>(); 

list.add("Ravi"); 

list.add("Vijay"); 

list.add("Ajay"); 



HashSet<String> set=new HashSet(list); 
set.add("Gaurav"); 
 Iterator<String> i=set.iterator(); 

while(i.hasNext()) 

{ 

System.out.println(i.next()); 

} 

} 

} 

Vijay 

Ravi 

Gaurav 

Ajay 

Java HashSet Example: Book 

We should see a HashSet model where we are adding books to set and printing every one of the books. 

import java.util.*; 

class Book { 

int id; 

String name,author,publisher; 

int amount; 

public Book(int id, String name, String writer, String distributer, int amount) { 

this.id = id; 

this.name = name; 

this.author = creator; 

this.publisher = distributer; 
this.quantity = amount; 

} 

} 

public class HashSetExample { 

public static void main(String[] args) { 
HashSet<Book> set=new HashSet<Book>(); 

/Creating Books 

 Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8); 

Book b2=new Book(102,"Data Communications and Networking","Forouzan","Mc Graw Hill",4); 

Book b3=new Book(103,"Operating System","Galvin","Wiley",6); 

/Adding Books to HashSet 

set.add(b1); 

set.add(b2); 

 set.add(b3); 

/Traversing HashSet 

for(Book b:set){ 

System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity); 

} 

} 

} 

Yield: 

101 Let us C Yashwant Kanetkar BPB 8 

102 Data Communications and Networking Forouzan Mc Graw Hill 4 

103 Operating System Galvin Wiley 6

Java LinkedHashSet class 

Java HashSet class pecking order 

Java LinkedHashSet class is a Hashtable and Linked rundown execution of the set interface. It acquires a HashSet class and carries out a Set interface. 

The significant focuses about Java LinkedHashSet class are: 

  • Java LinkedHashSet class contains interesting components just like HashSet. 
  • Java LinkedHashSet class gives all discretionary set activity and licenses invalid components. 
  • Java LinkedHashSet class is non synchronized. 
  • Java LinkedHashSet class keeps up inclusion request.

Pecking order of LinkedHashSet class 

The LinkedHashSet class expands to the HashSet class which carries out the Set interface. The Set interface acquires Collection and Iterable interfaces in various leveled requests.

LinkedHashSet class presentation 

How about we see the statement for java.util.LinkedHashSet class. 

1. public class LinkedHashSet<E> expands HashSet<E> carries out Set<E>, Cloneable, Serializable

ConstructorDescription 
HashSet()It is utilized to develop a default HashSet. 
HashSet(Collection c)It is utilized to instate the hash set by utilizing the components of the assortment c. 
LinkedHashSet(int capacity)It is utilized in state the limit of the connected hash set to the given whole number worth limit. 

LinkedHashSet(int limit, skim fillRatio) It is utilized to introduce both the limit and the fill proportion (additionally called load limit) of the hash set from its contention. 

Java LinkedHashSet Example 

We should see a basic illustration of Java LinkedHashSet class. Here you can see that the components repeat in the inclusion request.

import java.util.*; 

class LinkedHashSet1{ 

public static void main(String args[]){ 

/Creating HashSet and adding components 

LinkedHashSet<String> set=new LinkedHashSet(); 

set.add("One"); 

set.add("Two"); 

set.add("Three"); 

set.add("Four"); 

set.add("Five"); 

Iterator<String> i=set.iterator(); 

while(i.hasNext()) 

{ 

System.out.println(i.next()); 

} 

} 

} 

One 

Two 

Three 

Four 

Five

Java LinkedHashSet model disregarding copy Elements

import java.util.*; 

class LinkedHashSet2{ 

public static void main(String args[]){ 

LinkedHashSet<String> al=new LinkedHashSet<String>(); 

al.add("Ravi"); 

al.add("Vijay"); 

al.add("Ravi"); 

al.add("Ajay"); 

Iterator<String> itr=al.iterator(); 

while(itr.hasNext()){ 

System.out.println(itr.next()); 

} 

} 

} 

Ravi 

Vijay 

Ajay

Java LinkedHashSet Example: Book 

import java.util.*; 

class Book { 

int id; 

String name,author,publisher; 

int amount; 

public Book(int id, String name, String writer, String distributer, int amount) { 

this.id = id; 

this.name = name; 

this.author = creator; 

this.publisher = distributer; 

this.quantity = amount; 

} 

} 

public class LinkedHashSetExample { 

public static void main(String[] args) { 

LinkedHashSet<Book> hs=new LinkedHashSet<Book>(); 

/Creating Books 

Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8); 

Book b2=new Book(102,"Data Communications and Networking","Forouzan","Mc Graw Hill",4); 

Book b3=new Book(103,"Operating System","Galvin","Wiley",6); 

/Adding Books to hash table 

hs.add(b1); 

hs.add(b2); 

hs.add(b3); 
/Traversing hash table 

for(Book b:hs){ 

System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity); 

} 

} 

} 

Yield: 

101 Let us C Yashwant Kanetkar BPB 8 

102 Data Communications and Networking Forouzan Mc Graw Hill 4 

103 Operating System Galvin Wiley 6

This brings us to end of the blog on HashSet in Java. We hope that you were able to gain some valuable insights from the same. If you wish to learn more such concepts, join Great Learning Academy’s Free Online Courses and upskill today.

Engaging in the study of Java programming suggests a keen interest in the realm of software development. For those embarking upon this journey with aspirations towards a career in this field, it is recommended to explore the following pages in order to acquire a comprehensive understanding of the development career path:

Software engineering courses certificates
Software engineering courses placements
Software engineering courses syllabus
Software engineering courses fees
Software engineering courses eligibility
Avatar photo
Great Learning Team
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

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

Great Learning Free Online Courses
Scroll to Top