Which do you prefer? 1. `for (value in map.values...
# announcements
m
Which do you prefer? 1.
for (value in map.values) { … }
2.
for ((_, value) in map) { … }
1️⃣ 18
n
1
m
Apart from your question, there’s a side thought I came up recently regarding iterating maps: probably it shouldn’t be done and could be a sign that we’re using the wrong data structure for the job. A map lets us lookup a value from a known key in O(1) time but when we iterate through its entries we’re searching in O(n) time. Yes this probably isn’t perceivable at all for a small number of elements, but I found myself many times having a map but only iterating its entries searching for some key or value: I think that’s not the correct usage of maps, where the best performance comes from knowing the key beforehand. So for these cases I think using binary search on an array or a binary search tree would be best suited. But again, this argument is moot for small sets and we’re lazy (I for one!), so we just use maps. 😄
n
SortedMap & NavigableMap let you look up known keys in O(log n) and also find closest keys before/after a known value, select submaps by range of keys, etc.
1
👍 2
Can be useful when you would need to iterate through all keys in a hash map
e
I prefer map.forEach { (_, v) -> ... }?
👍 1
👎 1