A generic unordered collection of elements that does not support duplicate elements.
Set
implements Collection
and the methods inside this interface only supports read-only access to the set.
How we declare Set in Kotlin?
- Line 2 — we’ve declared an immutable set here.
- Line 3— we’ve added hero here,
QOP
(Queen Of Pain) - Line 4— we’ve added Windranger to our
setOfIntHeroes
but it doesn’t add to our set becauseset
cannot contain duplicate items and QOP didn’t appear becausesetOfIntHeroes
is immutable, we cannot really “add” items here.
Mutable Set
MutableSet
implements MutableCollection therefore you can use this if you want to add or remove item(s) in your set.
How we declare a Mutable Set in Kotlin?
For example, you have a text file that contains thousands of data, but you want to filter this out and remove the duplicate items.
I’ve created here a sample text file, dota_strength_heroes.txt
, put some of the strength type heroes, and add some duplicates.
- Line 2 — we’ve declared a mutable set named
setOfStrengthHeroes
- Line 3 — here, we implemented the
File
, a method of Java, to read our text filedota_strength_heroes.txt
. And we usedforEachLine
to iterate line by line inside this text file so that we can add each item tosetOfStrengthHeroes
mutable set. - Line 6 — we also iterate our set to print the output:
As we can see, the set did not append the duplicated items.
So yep, that’s it. It’s like maarte na list na ayaw ng may katulad. lol
Thanks! :D