https://kotlinlang.org logo
#codereview
Title
# codereview
a

Alexis Cala Martínez

01/20/2021, 5:57 AM
Hello how could i do this better
is this better?
m

Matteo Mirk

01/20/2021, 9:30 AM
You can further simplify this by providing just the key selector to associateBy and avoid referencing the concrete implementation:
Copy code
val mapSomeDTO = getSomeDTOList().associateBy { it.id }
a

Alexis Cala Martínez

01/20/2021, 1:58 PM
hello @Matteo Mirk good morning, thx for aswering
but i want a hashmap
m

Matteo Mirk

01/20/2021, 1:59 PM
why do you need to reference the concrete class instead of its interface?
in general you should prefer coupling to interfaces instead of implementations, but if you really have some reason for it, just use the other associateByTo overload
Copy code
val hashMapSomeDTO = getSomeDTOList().associateByTo(HashMap()) { it.id }
a

Alexis Cala Martínez

01/20/2021, 3:23 PM
What i really want is returning a map because later i have to used for complete another response, in order to do not use a find on a list i rather a hashmap, but really i want to decrease from O(n^2) to O(n)
m

Matteo Mirk

01/20/2021, 4:03 PM
I see, so there’s no reason to couple the client code to a specific implementation (HashMap), you can safely return a
Map
reference if all you need is a fast lookup by id. [By the way, a linear search on a list has an average complexity of O(n), but you can use a binary search which is O(log n)]
a

Alexis Cala Martínez

01/21/2021, 4:42 AM
yes for sure but elements on list are not ordered
m

Matteo Mirk

01/21/2021, 9:16 AM
Ah yes, sorry I overlooked that. Anyway you don’t start from O(n^2) complexity
4 Views