🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
In Kotlin, HashSet is a hash table-based implementation of the MutableSet interface. It provides a collection of unique elements and is part of the kotlin.collections package. HashSet is used for storing and managing data with efficient access, insertion, and deletion operations.
Table of Contents
- What is
HashSet? - Creating a
HashSet - Common Operations
- Examples of
HashSet - Real-World Use Case
- Conclusion
1. What is HashSet?
HashSet in Kotlin is a dynamic collection that allows you to store, access, and modify unique elements efficiently. It is part of the kotlin.collections package and implements the MutableSet interface.
2. Creating a HashSet
You can create a HashSet using the constructor or by initializing it with elements.
Example
val emptySet = HashSet<Int>() // Creates an empty HashSet
val setWithElements = hashSetOf(1, 2, 3, 4) // Creates a HashSet with elements
3. Common Operations
HashSet supports various operations for adding, removing, and accessing elements.
Adding Elements
add(element: E): Adds an element to the set. If the element already exists, it does nothing and returnsfalse.
Removing Elements
remove(element: E): Removes the specified element from the set.
Checking Elements
contains(element: E): Checks if the set contains the specified element.isEmpty(): Checks if the set is empty.isNotEmpty(): Checks if the set is not empty.
Accessing Elements
iterator(): Returns an iterator over the elements in the set.
Checking Size
size: Returns the number of elements in the set.
Clearing the Set
clear(): Removes all elements from the set.
4. Examples of HashSet
Example 1: Adding Elements
add(element: E)
This example demonstrates how to add elements to the set.
fun main() {
val set = HashSet<Int>()
set.add(1)
set.add(2)
set.add(3)
println("Set after adding elements: $set") // Output: Set after adding elements: [1, 2, 3]
}
Output:
Set after adding elements: [1, 2, 3]
Example 2: Removing Elements
remove(element: E)
This example demonstrates how to remove an element from the set.
fun main() {
val set = hashSetOf(1, 2, 3, 4)
set.remove(3)
println("Set after removing '3': $set") // Output: Set after removing '3': [1, 2, 4]
}
Output:
Set after removing '3': [1, 2, 4]
Example 3: Checking Elements
contains(element: E)
This example demonstrates how to check if the set contains a specified element.
fun main() {
val set = hashSetOf("apple", "banana", "cherry")
println("Set contains 'banana': ${set.contains("banana")}") // Output: Set contains 'banana': true
println("Set contains 'grape': ${set.contains("grape")}") // Output: Set contains 'grape': false
}
Output:
Set contains 'banana': true
Set contains 'grape': false
Example 4: Checking Size and Emptiness
size, isEmpty(), and isNotEmpty()
This example demonstrates how to check the size of the set and if it is empty.
fun main() {
val set = hashSetOf(10, 20, 30)
println("Size of set: ${set.size}") // Output: Size of set: 3
println("Is set empty: ${set.isEmpty()}") // Output: Is set empty: false
println("Is set not empty: ${set.isNotEmpty()}") // Output: Is set not empty: true
}
Output:
Size of set: 3
Is set empty: false
Is set not empty: true
Example 5: Iterating Over a Set
iterator()
This example demonstrates how to iterate over the elements in the set.
fun main() {
val set = hashSetOf('a', 'b', 'c', 'd')
val iterator = set.iterator()
while (iterator.hasNext()) {
println(iterator.next())
}
}
Output:
a
b
c
d
Explanation:
This example shows how to iterate over the elements in a set using an iterator.
Example 6: Clearing the Set
clear()
This example demonstrates how to remove all elements from the set.
fun main() {
val set = hashSetOf(100, 200, 300)
set.clear()
println("Set after clearing: $set") // Output: Set after clearing: []
}
Output:
Set after clearing: []
5. Real-World Use Case: Removing Duplicates from a List
You can use HashSet to remove duplicates from a list of elements.
Example: Removing Duplicates
fun main() {
val list = listOf(1, 2, 2, 3, 4, 4, 5)
val set = HashSet(list)
println("List with duplicates: $list") // Output: List with duplicates: [1, 2, 2, 3, 4, 4, 5]
println("Set without duplicates: $set") // Output: Set without duplicates: [1, 2, 3, 4, 5]
}
Output:
List with duplicates: [1, 2, 2, 3, 4, 4, 5]
Set without duplicates: [1, 2, 3, 4, 5]
Explanation:
This example converts a list with duplicates to a HashSet to remove the duplicate elements.
Conclusion
HashSet in Kotlin is a versatile and efficient dynamic collection from the kotlin.collections package, ideal for scenarios requiring unique elements and frequent modifications. Properly utilizing HashSet can greatly enhance the performance and flexibility of your applications.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment