How can I retrieve an item from a list and add it ...
# android
a
How can I retrieve an item from a list and add it if it does not exist and get its reference again? I guess I can do better than this.
Copy code
var playedPodcast = playedPodcasts.find {
    it.id == itemToPlay?.id
}
if (playedPodcast == null) {
    playedPodcasts.add(PlayedPodcast(itemToPlay?.id, mutableListOf()))
}
playedPodcast = playedPodcasts.find {
    it.id == itemToPlay?.id
}!!
c
You are basically building a map...if you use a map for
playedPodcasts
you can do
Copy code
val playedPodcasts = mutableMapOf<String, Podcast>(...)

val playedPodcast = playedPodcasts.getOrPut(itemToPlay.id) {
   PlayedPodcast(itemToPlay?.id, mutableListOf())
}
If you get a list from e.g. your backend you can do
Copy code
val playedPodcasts = listFromBackend.associate { podcast -> podcast.id to podcast }.toMutableMap()
a
Nice! But, is there a getOrPut list version? Something like getOrAdd?
That's because I have the same logic with a segments list in Podcast. Should I convert to map everytime I want to achieve this with a list?
c
You can use
getOrElse
on lists, but it wont add the value to the list. Your use case is just not suited for a list 😄 If you convert to a map every time you won't have the item in the map as well as you get a new map each time. Also might come with some performance impact
1
So ideally: Convert once to a map and then work on the map
1
a
I see, thanks.
d
You creating a reference when you add to played podcasts. Just save it in a variable and use it directly.
103 Views