Youssef Shoaib [MOD]
06/19/2022, 2:22 PMlist1.zip(list2).toMap()
but it turns them into pairs in the process and I don't quite like that. Is there a neater 1-liner for it? I looked at associateWtih and associateBy but I can't seem to get them to work for this use case.
Edit: Neatest one-liner I've found: (0..list1.lastIndex).associateBy(list1::get, list2::get)
Chris Lee
06/19/2022, 2:48 PMYoussef Shoaib [MOD]
06/19/2022, 3:09 PMzip
turns it into a List<Pair<A, B>>
. I want to avoid the creation of that list. In other words, I just want the map to be directly created out of my initial 2 lists. I can do this imperatively like so:
buildMap {
for(i in 0..list1.lastIndex){
put(list1[i], list2[i])
}
}
But I would like something neaterChris Lee
06/19/2022, 4:04 PM(list1 + list2).toMap
(or associateBy
etc)Youssef Shoaib [MOD]
06/19/2022, 6:45 PM(0..list1.lastIndex).associateBy(list1::get, list2::get)
ephemient
06/19/2022, 7:37 PMlist1.asSequence().zip(list2.asSequence()).toMap()
Youssef Shoaib [MOD]
06/19/2022, 7:39 PMephemient
06/19/2022, 7:42 PMList
but has other costs, including Pair
.Youssef Shoaib [MOD]
06/19/2022, 7:46 PMephemient
06/19/2022, 7:51 PMlist1.indices
is undoubtedly clearer, but I'd use 0 until minOf(list1.size, list2.size)
for consistency with zip
ephemient
06/19/2022, 7:54 PMYoussef Shoaib [MOD]
06/19/2022, 7:57 PMindices
. Thanks for all the suggestions. Tbh currently performance isn't that big of a goal, but obviously I don't want to write inefficient code that could very easily be optimised. I think going with indices will potentially be the most efficient (because an IntRange
seems quite cheap) and I think I might just define a fun maxOf(IntRange, IntRange)
To top it all off!ephemient
06/19/2022, 8:18 PMIntRange
in for (i in list1.indices)
or for (i in 0 until maxOf(list1.size, list2.size))
, but it won't (ending up going through the Iteratable
and Iterator
interfaces) in list1.indices.associateBy
or a custom maxOf(IntRange, IntRange)