Groovy - Map intersect(Map right) method
Description
Groovy Map intersect(Map right) method returns the intersection of both map as a map of common entries.
Syntax
public Map intersect(Map right)
Parameters
right − A Map
Return Value
Map as a intersection of both maps
Example - Getting Intersection of Maps of String and String
Following is an example of the usage of this method −
main.groovy
// define two maps def map = ["A" : "Apple", "B" : "Banana"] def map1 = ["B" : "Banana", "C": "Carrot", "D":"Berry"] // get intersection of two maps def result = map.intersect(map1) println(result)
Output
When we run the above program, we will get the following result −
[B:Banana]
Example - Getting Intersection of Maps of Integer and Integer
Following is an example of the usage of this method −
main.groovy
// define maps def map = [1 : 11, 2 : 12, 3: 13, 4:14] def map1 = [2 : 12, 3: 13, 4:14] // get intersection of two maps def result = map.intersect(map1) println(result)
Output
When we run the above program, we will get the following result −
[2:12, 3:13, 4:14]
Example - Getting Intersection of Maps of Integer and Object
Following is an example of the usage of this method −
main.groovy
// define maps
def map = [1 : new Student(1, "Julie"), 2 : new Student(2, "Robert"), 3: new Student(3,"Adam"),4: new Student(4,"Markus")]
def map1 = [3: new Student(3,"Adam"),4: new Student(4,"Markus")]
// get intersection of two maps
def result = map.intersect(map1)
println(result)
class Student{
int rollNo
String name
Student(int rollNo, String name){
this.rollNo = rollNo
this.name = name
}
@Override
public boolean equals(Object obj) {
Student s = (Student)obj
return this.rollNo == s.rollNo && this.name.equalsIgnoreCase(s.name)
}
@Override
public String toString() {
return "[ " + this.rollNo + ", " + this.name + " ]"
}
}
Output
When we run the above program, we will get the following result −
[3:[ 3, Adam ], 4:[ 4, Markus ]]
groovy_maps.htm
Advertisements