Hi all, I was wondering is there a better way to c...
# getting-started
a
Hi all, I was wondering is there a better way to create
set
or
distinct
lists from a list of objects based on their property? Currently I’m looping through each user and adding them one by one to the
set
Copy code
val userEmails = mutableSetOf<String>()
users.forEach {
    userEmails.add("Adding unique email: ${it.email}")
}
print(userEmails)
s
val userEmails = users.map { it.email }.toSet()
👍 2
❤️ 1
🤔 1
a
I saw
distinct
as well, does anyone knows performance wise whats the difference between the two?
Thanks all
s
Actually, sorry, what I posted doesn’t exactly do what you’d want
Campbell had it right the first time, more or less
a
Yes but if I created regular list I could use
distinct
to add unique values 🙂
s
performance-wise they’d be more or less identical, or at least they should on the JVM after a few runs
I’d be surprised if HotSpot couldn’t figure out what you were doing here
s
So to summarize, the following work:
users.map { it.email }.toSet() // returns Set
users.map { it.email }.distinct() // returns List
👍 1
thanks for making unnecessary changes to how markdown works, slack :)