Kotlin: Collections Part 2 — Set

MJ Manaog
2 min readJul 3, 2020

--

A generic unordered collection of elements that does not support duplicate elements.

Set Interface

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 because set cannot contain duplicate items and QOP didn’t appear because setOfIntHeroes is immutable, we cannot really “add” items here.

Mutable Set

MutableSet Interface

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.

dota_strength_heroes.txt
  • 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 file dota_strength_heroes.txt . And we used forEachLine to iterate line by line inside this text file so that we can add each item to setOfStrengthHeroes 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

--

--

MJ Manaog
MJ Manaog

No responses yet