Deep dive into HashSet , LinkedHashSet and TreeSet

Last updated on Dec 23 2022
Prabhas Ramanathan

java 28

Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements Set interface.
The important points about Java HashSet class are:
• HashSet stores the elements by using a mechanism called hashing.
• HashSet contains unique elements only.
• HashSet allows null value.
• HashSet class is non synchronized.
• HashSet doesn’t maintain the insertion order. Here, elements are inserted on the basis of their hashcode.
• HashSet is the best approach for search operations.
• The initial default capacity of HashSet is 16, and the load factor is 0.75.

Table of Contents

Difference between List and Set

A list can contain duplicate elements whereas Set contains unique elements only.

Hierarchy of HashSet class

The HashSet class extends AbstractSet class which implements Set interface. The Set interface inherits Collection and Iterable interfaces in hierarchical order.

HashSet class declaration

Let’s see the declaration for java.util.HashSet class.
1. public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable

Constructors of Java HashSet class

SN Constructor Description
1) HashSet() It is used to construct a default HashSet.
2) HashSet(int capacity) It is used to initialize the capacity of the hash set to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet.
3) HashSet(int capacity, float loadFactor) It is used to initialize the capacity of the hash set to the given integer value capacity and the specified load factor.
4) HashSet(Collection<? extends E> c) It is used to initialize the hash set by using the elements of the collection c.

Methods of Java HashSet class

Various methods of Java HashSet class are as follows:

SN Modifier & Type Method Description
1) boolean add(E e) It is used to add the specified element to this set if it is not already present.
2) void clear() It is used to remove all of the elements from the set.
3) object clone() It is used to return a shallow copy of this HashSet instance: the elements themselves are not cloned.
4) boolean contains(Object o) It is used to return true if this set contains the specified element.
5) boolean isEmpty() It is used to return true if this set contains no elements.
6) Iterator<E> iterator() It is used to return an iterator over the elements in this set.
7) boolean remove(Object o) It is used to remove the specified element from this set if it is present.
8) int size() It is used to return the number of elements in the set.
9) Spliterator<E> spliterator() It is used to create a late-binding and fail-fast Spliterator over the elements in the set.

Java HashSet Example

Let’s see a simple example of HashSet. Notice, the elements iterate in an unordered collection.
1. import java.util.*;
2. class HashSet1{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet();
6. set.add(“One”);
7. set.add(“Two”);
8. set.add(“Three”);
9. set.add(“Four”);
10. set.add(“Five”);
11. Iterator<String> i=set.iterator();
12. while(i.hasNext())
13. {
14. System.out.println(i.next());
15. }
16. }
17. }
Five
One
Four
Two
Three

Java HashSet example ignoring duplicate elements

In this example, we see that HashSet doesn’t allow duplicate elements.
1. import java.util.*;
2. class HashSet2{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet<String>();
6. set.add(“Ravi”);
7. set.add(“Vijay”);
8. set.add(“Ravi”);
9. set.add(“Ajay”);
10. //Traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Ajay
Vijay
Ravi

Java HashSet example to remove elements

Here, we see different ways to remove an element.
1. import java.util.*;
2. class HashSet3{
3. public static void main(String args[]){
4. HashSet<String> set=new HashSet<String>();
5. set.add(“Ravi”);
6. set.add(“Vijay”);
7. set.add(“Arun”);
8. set.add(“Sumit”);
9. System.out.println(“An initial list of elements: “+set);
10. //Removing specific element from HashSet
11. set.remove(“Ravi”);
12. System.out.println(“After invoking remove(object) method: “+set);
13. HashSet<String> set1=new HashSet<String>();
14. set1.add(“Ajay”);
15. set1.add(“Gaurav”);
16. set.addAll(set1);
17. System.out.println(“Updated List: “+set);
18. //Removing all the new elements from HashSet
19. set.removeAll(set1);
20. System.out.println(“After invoking removeAll() method: “+set);
21. //Removing elements on the basis of specified condition
22. set.removeIf(str->str.contains(“Vijay”));
23. System.out.println(“After invoking removeIf() method: “+set);
24. //Removing all the elements available in the set
25. set.clear();
26. System.out.println(“After invoking clear() method: “+set);
27. }
28. }
An initial list of elements: [Vijay, Ravi, Arun, Sumit]
After invoking remove(object) method: [Vijay, Arun, Sumit]
Updated List: [Vijay, Arun, Gaurav, Sumit, Ajay]
After invoking removeAll() method: [Vijay, Arun, Sumit]
After invoking removeIf() method: [Arun, Sumit]
After invoking clear() method: []

Java HashSet from another Collection

1. import java.util.*;
2. class HashSet4{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add(“Ravi”);
6. list.add(“Vijay”);
7. list.add(“Ajay”);
8.
9. HashSet<String> set=new HashSet(list);
10. set.add(“Gaurav”);
11. Iterator<String> i=set.iterator();
12. while(i.hasNext())
13. {
14. System.out.println(i.next());
15. }
16. }
17. }
Vijay
Ravi
Gaurav
Ajay

Java HashSet Example: Book

Let’s see a HashSet example where we are adding books to set and printing all the books.
1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class HashSetExample {
15. public static void main(String[] args) {
16. HashSet<Book> set=new HashSet<Book>();
17. //Creating Books
18. Book b1=new Book(101,”Let us C”,”Yashwant Kanetkar”,”BPB”,8);
19. Book b2=new Book(102,”Data Communications & Networking”,”Forouzan”,”Mc Graw Hill”,4);
20. Book b3=new Book(103,”Operating System”,”Galvin”,”Wiley”,6);
21. //Adding Books to HashSet
22. set.add(b1);
23. set.add(b2);
24. set.add(b3);
25. //Traversing HashSet
26. for(Book b:set){
27. System.out.println(b.id+” “+b.name+” “+b.author+” “+b.publisher+” “+b.quantity);
28. }
29. }
30. }
Output:
101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

Java LinkedHashSet class

java 29

Java LinkedHashSet class is a Hashtable and Linked list implementation of the set interface. It inherits HashSet class and implements Set interface.
The important points about Java LinkedHashSet class are:
• Java LinkedHashSet class contains unique elements only like HashSet.
• Java LinkedHashSet class provides all optional set operation and permits null elements.
• Java LinkedHashSet class is non synchronized.
• Java LinkedHashSet class maintains insertion order.

Hierarchy of LinkedHashSet class

The LinkedHashSet class extends HashSet class which implements Set interface. The Set interface inherits Collection and Iterable interfaces in hierarchical order.

LinkedHashSet class declaration

Let’s see the declaration for java.util.LinkedHashSet class.
1. public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, Serializable

Constructors of Java LinkedHashSet class

Constructor Description
HashSet() It is used to construct a default HashSet.
HashSet(Collection c) It is used to initialize the hash set by using the elements of the collection c.
LinkedHashSet(int capacity) It is used initialize the capacity of the linked hash set to the given integer value capacity.
LinkedHashSet(int capacity, float fillRatio) It is used to initialize both the capacity and the fill ratio (also called load capacity) of the hash set from its argument.

Java LinkedHashSet Example

Let’s see a simple example of Java LinkedHashSet class. Here you can notice that the elements iterate in insertion order.
1. import java.util.*;
2. class LinkedHashSet1{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. LinkedHashSet<String> set=new LinkedHashSet();
6. set.add(“One”);
7. set.add(“Two”);
8. set.add(“Three”);
9. set.add(“Four”);
10. set.add(“Five”);
11. Iterator<String> i=set.iterator();
12. while(i.hasNext())
13. {
14. System.out.println(i.next());
15. }
16. }
17. }
One
Two
Three
Four
Five

Java LinkedHashSet example ignoring duplicate Elements

1. import java.util.*;
2. class LinkedHashSet2{
3. public static void main(String args[]){
4. LinkedHashSet<String> al=new LinkedHashSet<String>();
5. al.add(“Ravi”);
6. al.add(“Vijay”);
7. al.add(“Ravi”);
8. al.add(“Ajay”);
9. Iterator<String> itr=al.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
Ravi
Vijay
Ajay

Java LinkedHashSet Example: Book

1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class LinkedHashSetExample {
15. public static void main(String[] args) {
16. LinkedHashSet<Book> hs=new LinkedHashSet<Book>();
17. //Creating Books
18. Book b1=new Book(101,”Let us C”,”Yashwant Kanetkar”,”BPB”,8);
19. Book b2=new Book(102,”Data Communications & Networking”,”Forouzan”,”Mc Graw Hill”,4);
20. Book b3=new Book(103,”Operating System”,”Galvin”,”Wiley”,6);
21. //Adding Books to hash table
22. hs.add(b1);
23. hs.add(b2);
24. hs.add(b3);
25. //Traversing hash table
26. for(Book b:hs){
27. System.out.println(b.id+” “+b.name+” “+b.author+” “+b.publisher+” “+b.quantity);
28. }
29. }
30. }
Output:
101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

Java TreeSet class

java 30

Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements the NavigableSet interface. The objects of the TreeSet class are stored in ascending order.
The important points about Java TreeSet class are:
• Java TreeSet class contains unique elements only like HashSet.
• Java TreeSet class access and retrieval times are quiet fast.
• Java TreeSet class doesn’t allow null element.
• Java TreeSet class is non synchronized.
• Java TreeSet class maintains ascending order.

Hierarchy of TreeSet class

As shown in the above diagram, Java TreeSet class implements the NavigableSet interface. The NavigableSet interface extends SortedSet, Set, Collection and Iterable interfaces in hierarchical order.

TreeSet class declaration

Let’s see the declaration for java.util.TreeSet class.
1. public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, Serializable

Constructors of Java TreeSet class

Constructor Description
TreeSet() It is used to construct an empty tree set that will be sorted in ascending order according to the natural order of the tree set.
TreeSet(Collection<? extends E> c) It is used to build a new tree set that contains the elements of the collection c.
TreeSet(Comparator<? super E> comparator) It is used to construct an empty tree set that will be sorted according to given comparator.
TreeSet(SortedSet<E> s) It is used to build a TreeSet that contains the elements of the given SortedSet.

Methods of Java TreeSet class

Method Description
boolean add(E e) It is used to add the specified element to this set if it is not already present.
boolean addAll(Collection<? extends E> c) It is used to add all of the elements in the specified collection to this set.
E ceiling(E e) It returns the equal or closest greatest element of the specified element from the set, or null there is no such element.
Comparator<? super E> comparator() It returns comparator that arranged elements in order.
Iterator descendingIterator() It is used iterate the elements in descending order.
NavigableSet descendingSet() It returns the elements in reverse order.
E floor(E e) It returns the equal or closest least element of the specified element from the set, or null there is no such element.
SortedSet headSet(E toElement) It returns the group of elements that are less than the specified element.
NavigableSet headSet(E toElement, boolean inclusive) It returns the group of elements that are less than or equal to(if, inclusive is true) the specified element.
E higher(E e) It returns the closest greatest element of the specified element from the set, or null there is no such element.
Iterator iterator() It is used to iterate the elements in ascending order.
E lower(E e) It returns the closest least element of the specified element from the set, or null there is no such element.
E pollFirst() It is used to retrieve and remove the lowest(first) element.
E pollLast() It is used to retrieve and remove the highest(last) element.
Spliterator spliterator() It is used to create a late-binding and fail-fast spliterator over the elements.
NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) It returns a set of elements that lie between the given range.
SortedSet subSet(E fromElement, E toElement)) It returns a set of elements that lie between the given range which includes fromElement and excludes toElement.
SortedSet tailSet(E fromElement) It returns a set of elements that are greater than or equal to the specified element.
NavigableSet tailSet(E fromElement, boolean inclusive) It returns a set of elements that are greater than or equal to (if, inclusive is true) the specified element.
boolean contains(Object o) It returns true if this set contains the specified element.
boolean isEmpty() It returns true if this set contains no elements.
boolean remove(Object o) It is used to remove the specified element from this set if it is present.
void clear() It is used to remove all of the elements from this set.
Object clone() It returns a shallow copy of this TreeSet instance.
E first() It returns the first (lowest) element currently in this sorted set.
E last() It returns the last (highest) element currently in this sorted set.
int size() It returns the number of elements in this set.

Java TreeSet Examples

Java TreeSet Example 1:

Let’s see a simple example of Java TreeSet.
1. import java.util.*;
2. class TreeSet1{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> al=new TreeSet<String>();
6. al.add(“Ravi”);
7. al.add(“Vijay”);
8. al.add(“Ravi”);
9. al.add(“Ajay”);
10. //Traversing elements
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Test it Now
Output:
Ajay
Ravi
Vijay

Java TreeSet Example 2:

Let’s see an example of traversing elements in descending order.
1. import java.util.*;
2. class TreeSet2{
3. public static void main(String args[]){
4. TreeSet<String> set=new TreeSet<String>();
5. set.add(“Ravi”);
6. set.add(“Vijay”);
7. set.add(“Ajay”);
8. System.out.println(“Traversing element through Iterator in descending order”);
9. Iterator i=set.descendingIterator();
10. while(i.hasNext())
11. {
12. System.out.println(i.next());
13. }
14.
15. }
16. }
Test it Now
Output:
Traversing element through Iterator in descending order
Vijay
Ravi
Ajay
Traversing element through NavigableSet in descending order
Vijay
Ravi
Ajay

Java TreeSet Example 3:

Let’s see an example to retrieve and remove the highest and lowest Value.
1. import java.util.*;
2. class TreeSet3{
3. public static void main(String args[]){
4. TreeSet<Integer> set=new TreeSet<Integer>();
5. set.add(24);
6. set.add(66);
7. set.add(12);
8. set.add(15);
9. System.out.println(“Highest Value: “+set.pollFirst());
10. System.out.println(“Lowest Value: “+set.pollLast());
11. }
12. }
Output:
Highest Value: 12
Lowest Value: 66

Java TreeSet Example 4:

In this example, we perform various NavigableSet operations.
1. import java.util.*;
2. class TreeSet4{
3. public static void main(String args[]){
4. TreeSet<String> set=new TreeSet<String>();
5. set.add(“A”);
6. set.add(“B”);
7. set.add(“C”);
8. set.add(“D”);
9. set.add(“E”);
10. System.out.println(“Initial Set: “+set);
11.
12. System.out.println(“Reverse Set: “+set.descendingSet());
13.
14. System.out.println(“Head Set: “+set.headSet(“C”, true));
15.
16. System.out.println(“SubSet: “+set.subSet(“A”, false, “E”, true));
17.
18. System.out.println(“TailSet: “+set.tailSet(“C”, false));
19. }
20. }
Output:
Initial Set: [A, B, C, D, E]
Reverse Set: [E, D, C, B, A]
Head Set: [A, B, C]
SubSet: [B, C, D, E]
TailSet: [D, E]

Java TreeSet Example 4:

In this example, we perform various SortedSetSet operations.
1. import java.util.*;
2. class TreeSet4{
3. public static void main(String args[]){
4. TreeSet<String> set=new TreeSet<String>();
5. set.add(“A”);
6. set.add(“B”);
7. set.add(“C”);
8. set.add(“D”);
9. set.add(“E”);
10.
11. System.out.println(“Intial Set: “+set);
12.
13. System.out.println(“Head Set: “+set.headSet(“C”));
14.
15. System.out.println(“SubSet: “+set.subSet(“A”, “E”));
16.
17. System.out.println(“TailSet: “+set.tailSet(“C”));
18. }
19. }
Output:
Intial Set: [A, B, C, D, E]
Head Set: [A, B]
SubSet: [A, B, C, D]
TailSet: [C, D, E]

Java TreeSet Example: Book

Let’s see a TreeSet example where we are adding books to set and printing all the books. The elements in TreeSet must be of a Comparable type. String and Wrapper classes are Comparable by default. To add user-defined objects in TreeSet, you need to implement the Comparable interface.
1. import java.util.*;
2. class Book implements Comparable<Book>{
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. public int compareTo(Book b) {
14. if(id>b.id){
15. return 1;
16. }else if(id<b.id){
17. return -1;
18. }else{
19. return 0;
20. }
21. }
22. }
23. public class TreeSetExample {
24. public static void main(String[] args) {
25. Set<Book> set=new TreeSet<Book>();
26. //Creating Books
27. Book b1=new Book(121,”Let us C”,”Yashwant Kanetkar”,”BPB”,8);
28. Book b2=new Book(233,”Operating System”,”Galvin”,”Wiley”,6);
29. Book b3=new Book(101,”Data Communications & Networking”,”Forouzan”,”Mc Graw Hill”,4);
30. //Adding Books to TreeSet
31. set.add(b1);
32. set.add(b2);
33. set.add(b3);
34. //Traversing TreeSet
35. for(Book b:set){
36. System.out.println(b.id+” “+b.name+” “+b.author+” “+b.publisher+” “+b.quantity);
37. }
38. }
39. }
Output:
101 Data Communications & Networking Forouzan Mc Graw Hill 4
121 Let us C Yashwant Kanetkar BPB 8
233 Operating System Galvin Wiley 6

So, this brings us to the end of blog. This Tecklearn ‘Deep dive into HashSet , LinkedHashSet and TreeSet in Java’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Java and JEE Training

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread

File Handling in Java

• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

0 responses on "Deep dive into HashSet , LinkedHashSet and TreeSet"

Leave a Message

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