Saturday 26 January 2019

Groovy: Get intersection of two lists


Groovy provides 'intersect' method, that returns the intersection of both iterables.

public Collection intersect(Iterable right)
Returns a Collection that is an intersection of both iterables.

HelloWorld.groovy
primes = [2, 3, 5, 7, 11, 13, 17, 19]
oddNumbers = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23]

oddPrimes = oddNumbers.intersect(primes)

println "primes : $primes"
println "oddNumbers : $oddNumbers"
println "oddPrimes : $oddPrimes"

Output
primes : [2, 3, 5, 7, 11, 13, 17, 19]
oddNumbers : [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23]
oddPrimes : [3, 5, 7, 11, 13, 17, 19]

How to get intersection of custom objects?
By implementing Comparable interface, you can get the intersection of custom objects.


HelloWorld.groovy
class Employee implements Comparable<Employee>{
 int id
 String name

 Employee(int id, String name){
  this.id = id
  this.name = name
 }

 String toString(){
  return this.id + ","+this.name
 }

    public int compareTo(Employee o) {
        if(o == null)
            throw new NullPointerException();
       return this.id.compareTo(o.id);
    }
    
}


list1 = [new Employee(1, "Krishna"), new Employee(2, "Ram")]
list2 = [new Employee(2, "Ram"), new Employee(3, "Joel")]

list3 = list1.intersect(list2)

println "$list3"

Output
[2,Ram]



Previous                                                 Next                                                 Home

No comments:

Post a Comment