Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two Maps in Scala

Is there any pre-defined function that I can use to compare two Maps based on the key and give me the difference? Right now, I iterate Map1 and foreach key, I check if there is an element in Map2 and I pattern match to find the difference. Is there a much elegant way to do this?

like image 215
joesan Avatar asked Jul 18 '14 14:07

joesan


People also ask

How do you compare two Hashmaps by their keys?

If we want to compare hashmaps by keys i.e. two hashmaps will be equals if they have exactly same set of keys, we can use HashMap. keySet() function. It returns all the map keys in HashSet. We can compare the hashset of keys for both maps using Set.

What is Scala map function?

Advertisements. map() method is a member of TraversableLike trait, it is used to run a predicate method on each elements of a collection. It returns a new collection.


1 Answers

Consider the difference between the maps converted into sets of tuples,

(m1.toSet diff m2.toSet).toMap
like image 179
elm Avatar answered Sep 29 '22 01:09

elm