Groovy - List minus(Collection removeMe) method
Description
Groovy List minus(Collection removeMe) method creates a new List composed of the elements of the original without those specified in the collection.
Syntax
List minus(Collection removeMe)
Parameters
removeMe − The collection of values to minus from the list.
Return Value
New list of values.
Example - Getting sublist of integers
Following is an example of the usage of this method −
main.groovy
def lst = [11, 12, 13, 14]; def newlst = []; newlst = lst.minus([12,13]); println(newlst); newlst = lst - [12,13]; println(newlst);
Output
When we run the above program, we will get the following result −
[11, 14] [11, 14]
Example - Getting sublist of strings
Following is an example of the usage of this method −
main.groovy
def lst = ["Apple", "Peach", "Orange", "Mango"]; def newlst = []; newlst = lst.minus(["Orange","Mango"]); println(newlst); newlst = lst - ["Orange","Mango"]; println(newlst);
Output
When we run the above program, we will get the following result −
[Apple, Peach] [Apple, Peach]
Example - Getting sublist of objects
Following is an example of the usage of this method −
main.groovy
def lst = [new Student(1, "Julie"),new Student(2, "Robert"),new Student(3, "Adam")];
def newlst = [];
newlst = lst.minus([new Student(2, "Robert")]);
println(newlst);
newlst = lst - [new Student(2, "Robert")];
println(newlst);
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 −
[[ 1, Julie ], [ 3, Adam ]] [[ 1, Julie ], [ 3, Adam ]]
groovy_lists.htm
Advertisements