Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagegroovy
linenumberstrue
HashSet set = [1,2,3]

//Append a value at the end of the set
set.add(4) == [1,2,3,4]

//Get an element at a specified location
set.getAt(2)

//Contains an element
set.contains(4) == true

//Check whether the set is empty
set.isEmpty() ==  false

//Remove an element
set.minus(3)

//Add an element
set.plus(5)

//Size of the set
set.size() == 4

//Max and min in the set
set.max() == 4
set.min() == 1

//Find for the first element matching the condition
set.find{   it > 1 } //returns 2

//Find for all elements matching the condition
set.findAll{
  it > 1 } //returns [2,3,4]

//Returns true if all elements match
set.every { it < 5 }

//Returns true if any element matches
set.any { it > 2 }


HashSet set1 = ["a", "b", "c", "d", "e"]
//Find index of 1st element matching criteria
set1.findIndexOf {
  it in ["c", "e", "g"] } //returns 2

//Index returned
set1.indexOf("c") == 2


//Sum of all the elements
set.sum() == 21
set1.sum() == "abcde"

//Join the elements
set.join('-') == "1-2-3"

HashSet set2 = [["a", "b"],["c", "d"]]
set2.sum() == ["a", "b", "c", "d"]


List

All the methods that apply to a Set are applicable to a List too. Some additional methods for List with examples are explained below. See here for all the methods applicable for a List.

Code Block
languagegroovy
linenumberstrue
def list = [1,2,3]

//AppendReverse a value at the end of the list
list.add(4list
list.reverse() == [14,2, 3,4]
list == [1,2,3,4]

//Contains an element
list.contains(4) == true

//Get an element at a specified location
list.get(2) == 3

//Check whether the list is empty
list.isEmpty() ==  false

//Remove an element
list.minus(3) == [1, 2, 4]

//Add an element
list.plus(5) == [1, 2, 3, 4, 5]

//Reverse a list
list.reverse() == [4, 3, 2, 1]

//Size of the list
list.size() == 4

//Max and min in the list
list.max() == 4
list.min() == 1

//Find for the first element matching the condition
[1,2,3].find{
  it > 1
}
//returns 2

//Find for all elements matching the condition
[1,2,3].findAll{
  it > 1
}
//returns [2,3]

//Find index of 1st element matching criteria
["a", "b", "c", "d", "e"].findIndexOf {
  it in ["c", "e", "g"]
}
//returns 2

//Index returned
["a", "b", "c", "d", "c"].indexOf("c") == 2

//Returns true if all elements match
[1, 2, 3].every { it < 5 }

//Returns true if any element matches
[1, 2, 3].any { it > 2 }

//Sum of all the elements
[1, 2, 3, 4, 5, 6].sum() == 21
["a", "b", "c", "d", "e"].sum() == "abcde"
[["a", "b"],["c", "d"]].sum() == 2, 1]

//Index returned
["a", "b", "c", "d", "c"].indexOf("c") == 2

//Join the elements
[1, 2, 3].join('-') == "1-2-3"Get an element at a specified location
list.get(2)

Maps

Some useful methods with examples are explained below. See here for all the methods applicable for a Map.

...