Thursday 23 April 2020

Kotlin : Collections Set & HashSet (Post 18)

Hi  ,

Here I am again going to share how Set and HashSet are working in Kotlin .

Let's take a look first what is Set and HashSet :

Set : Always contains unique elements

HashSet : Always contains unique elements , and output sequence is not guaranteed .

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        /**
         * Set -> contains unique elements
         * HashSet -> contains unique elements ,but sequence is not same
         */
        //immutable , fixed size , Read only operation
        var mySet = setOf<Int>(13, 4, 32 , 2, 2, 2 , 5, 8 , 13)
        for (element in mySet) {
            println("Immutable Elements: $element ")
        }

        //mutable ,not fixed in size ,Read & Write Operations
        var mutableSet1 = hashSetOf<Int>()
        var mutableSet = mutableSetOf<Int>(13, 4, 32 , 2, 2, 2 , 5, 8 , 13)
        mutableSet.add(56)
        mutableSet.remove(5)

        for (element in mutableSet) {
            println("mutable Elements : $element")
        }
    }

Output :

Immutable Elements: 13 
Immutable Elements: 4 
Immutable Elements: 32 
Immutable Elements: 2 
Immutable Elements: 5 
Immutable Elements: 8 
mutable Elements : 13
mutable Elements : 4
mutable Elements : 32
mutable Elements : 2
mutable Elements : 8
mutable Elements : 56

Here we can see the for Immutable section

  •  all the elements sequence is same as input , 
  • the duplicate elements has been removed ! 

But for mutable section :

  • The duplicates elements are removed 
  • Input Elements sequence have been changed
  • Element 5 has been removed using .remove() operation
  • Element 56 has been added using .add() operation
So this is the simple example of Set and HashSet in Kotlin , this will help to get a basic understanding. In next post I will again explore 1 interesting topic in Kotlin , till then Happy Coding 😀😀




No comments:

Post a Comment

Advanced Kotlin Coroutines : Introduction

 Hi,  Today I am unwraping the topic in Kotin world i.e. Coroutine . If you want to get started with Kotlin coroutine and ease your daily de...