Best way to merge two maps and sum the values of same key?
The shortest answer I know of that uses only the standard library is map1 ++ map2.map{ case (k,v) => k -> (v + map1.getOrElse(k,0)) }
The shortest answer I know of that uses only the standard library is map1 ++ map2.map{ case (k,v) => k -> (v + map1.getOrElse(k,0)) }
The standard associative-container erase idiom: for (auto it = m.cbegin(); it != m.cend() /* not hoisted */; /* no increment */) { if (must_delete) { m.erase(it++); // or “it = m.erase(it)” since C++11 } else { ++it; } } Note that we really want an ordinary for loop here, since we are modifying the container … Read more
The map method takes an enumerable object and a block, and runs the block for each element, outputting each returned value from the block (the original object is unchanged unless you use map!): [1, 2, 3].map { |n| n * n } #=> [1, 4, 9] Array and Range are enumerable types. map with a … Read more
As long as the map is not a multimap, one of the most elegant ways would be to use the count method if (m.count(key)) // key exists The count would be 1 if the element is indeed present in the map.
As mentioned by others, the reason why get(), etc. is not generic because the key of the entry you are retrieving does not have to be the same type as the object that you pass in to get(); the specification of the method only requires that they be equal. This follows from how the equals() … Read more
There’s no difference, in fact map is implemented in C as rb_ary_collect and enum_collect (eg. there is a difference between map on an array and on any other enum, but no difference between map and collect). Why do both map and collect exist in Ruby? The map function has many naming conventions in different languages. … Read more
I prefer visual presentation: Property HashMap TreeMap LinkedHashMap Iteration Order no guaranteed order, will remain constant over time sorted according to the natural ordering insertion-order Get / put / remove / containsKey O(1) O(log(n)) O(1) Interfaces Map NavigableMap, Map, SortedMap Map Null values/keys allowed only values allowed Fail-fast behavior Fail-fast behavior of an iterator cannot … Read more