Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - List



The List is a structure used to store a collection of data items. In Groovy, the List holds a sequence of object references. Object references in a List occupy a position in the sequence and are distinguished by an integer index. A List literal is presented as a series of objects separated by commas and enclosed in square brackets.

To process the data in a list, we must be able to access individual elements. Groovy Lists are indexed using the indexing operator []. List indices start at zero, which refers to the first element.

Following are some example of lists −

  • [11, 12, 13, 14] A list of integer values
  • [Angular, Groovy, Java] A list of Strings
  • [1, 2, [3, 4], 5] A nested list
  • [Groovy, 21, 2.11] A heterogeneous list of object references
  • [ ] An empty list

In this chapter, we will discuss the list methods available in Groovy.

Sr.No. Methods & Description
1 add((Object value)

Append the new value to the end of this List.

2 add(int index, Object value)

Append the new value at a given index of this List.

3 addAll(int index, Object[] items)

Inserts all the items at provided index in this List.

4 asImmutable()

Returns an immutable version of this List.

5 asReversed()

Returns an reversed version of this List without modifying the original one.

6 asUnmodifiable()

Returns an unmodifiable version of this List.

7 contains()

Returns true if this List contains the specified value.

8 drop(int num)

Drops the given number of elements from the head of the list and returns the remaining items.

9 dropRight(int num)

Drops the given number of elements from the tail of the list and returns the remaining items.

10 dropWhile(Closure condition)

Drops the elements from the list which satisfy the given condition and returns the remaining items.

11 each(Closure closure)

Iterate the list, while passing each item to the closure.

12 eachWithIndex(Closure closure)

Iterate the list, while passing each item and an index to the closure.

13 equals(Object[] right)

Checks if contents of current list is same as content of provided array in same order. If collectiion is null, it returns false.

14 equals(List right)

Checks if contents of current list is same as content of provided list in same order. If collectiion is null, it returns false.

15 findAll()

Finds the items of the List which are matching Groovy Truth.

17 findall(Closure closure)

Finds the items of the List which are matching the given closure.

18 first()

Returns the first item of the List.

19 flatten()

Flattens the List. Current list with nested array or collection are flattened and a new list is returned.

20 getAt(EmptyRange range)

Supports the range subscript operator for the list.

21 getAt(Range range)

Supports the range subscript operator for the list.

22 getAt(int idx)

Returns the element of the List at given index.

23 getAt(Number idx)

Returns the element of the List at given index.

24 getAt(Collection indices)

Returns the elements of the List using the given indices.

22 get()

Returns the element at the specified position in this List.

23 grep()

Finds the items of the List which are matching Groovy Truth.

24 grep(Object filter)

Finds the items of the List which are matching the given filter.

25 head()

Returns the first item from the List.

26 init()

Returns the items from the List excluding last item.

27 intersect(Iterable right)

Returns the list of items which are common in current list and passed iterable.

28 intersect(Iterable right, Comparator comparator)

Returns the list of items which are common in current list and passed iterable, compared using passed comparator.

29 last()

Returns the last item of the List.

30 leftShift(Object value)

Overloads the left shift operator to append an object to the list easily.

31 isEmpty()

Returns true if this List contains no elements

32 minus(Collection removeMe)

Creates a new List composed of the elements of the original without those specified in the collection.

33 minus(Iterable removeMe)

Creates a new List composed of the elements of the original without those specified in the iterable.

34 minus(Object removeMe)

Creates a new List composed of the elements of the original without the passed object.

35 multiply(Factor factor)

Creates a new List composed of the elements of the original repeated the number of times the factor passed.

36 plus(Object right)

Creates a new List composed of the elements of the original together with the object.

37 plus(Collection collection)

Creates a new List composed of the elements of the original together with those specified in the collection.

38 plus(Iterable iterable)

Creates a new List composed of the elements of the original together with those specified in the iterable.

39 plus(int index, Iterable additions)

Creates a new List composed of the elements of the original together with those specified in the iterable at a given index.

40 plus(int index, Object[] items)

Creates a new List composed of the elements of the original together with those specified in the array at a given index.

41 plus(int index, List additions)

Creates a new List composed of the elements of the original together with those specified in the list at a given index.

42 pop()

Removes the last item from this List

43 push()

Appends an item to the end of the list.

44 removeAt(int index)

Removes the element at the specified position in this List.

45 remove(int index)

Removes the element at the specified position in this List.

46 removeLast()

Removes the last element from this List.

47 reverse()

Create a new List that is the reverse the elements of the original List

48 reverse(boolean mutate)

Create a new List that is the reverse the elements of the original List without modifying the original list if mutate is false else original list is modiifed as well.

49 reverseEach(Closure closure)

Iterates over list in reverse order and passes each element to the closure.

50 shuffle()

Reorders the elements of the List in random order.

51 shuffle()

Reorders the elements of the List in random order.

52 shuffle(Random random)

Reorders the elements of the List in random order using given Random instance.

53 shuffled()

Returns the reordered elements of the List in random order.

54 shuffled(Random random)

Return the reordered elements of the List in random order using given Random instance.

55 sort()

Returns a sorted copy of the original List.

56 split(Closure condition)

Splits the list into two collections based on given condition. First list contains the matched items and second list contains the unmatched one.

57 subsequences()

Returns a Set of all possible subsequences of the list items.

58 swap(int i, int j)

Swaps two elements of the List at given positions.

59 tail()

Returns the items from the current list excluding the first item.

60 take(int num)

Returns the first num elements from the list.

61 takeRight(int num)

Returns the last num elements from the tail of the list.

62 takeWhile(int num)

Returns the last num elements from the tail of the list.

63 toUnique()

Returns the list of unique elements while removing the duplicates as per the natural ordering of the elements.

64 toUnique(Closure condition)

Returns the list of unique elements while removing the duplicates as per the ordering specified by the Closure.

65 toUnique(Comparator comparator)

Returns the list of unique elements while removing the duplicates as per the ordering specified by the comparator.

66 transpose()

Takes list as collection of columns and transposes them to collection of rows. First row contains the first element from each column and so on.

67 unique()

Removes the duplicate items from the List.

68 unique(boolean mutate)

Removes the duplicate items from the List. If mutate is false, then original list is not modified else it is updated as well.

69 unique(boolean mutate, Closure closure)

Removes the duplicate items from the List using the Closure. If mutate is false, then original list is not modified else it is updated as well.

70 unique(boolean mutate, Comparator comparator)

Removes the duplicate items from the List using the comparator. If mutate is false, then original list is not modified else it is updated as well.

71 unique(Closure closure)

Removes the duplicate items from the List using the Closure. Original list is modified.

72 unique(Comparator comparator)

Removes the duplicate items from the List using the comparator. Original List is modified.

73 withDefault(Closure init)

An alias for withLazyDefault() method. Decorates the list allowing it to grow when a non-existing index is referred outside the normal list bounds.

74 withEagerDefault(Closure init)

Decorates the list allowing it to grow when a non-existing index is referred outside the normal list bounds. List is grown with default values.

75 withLazyDefault(Closure init)

Decorates the list allowing it to grow when a non-existing index is referred outside the normal list bounds.

Example - Adding Element to List of Integers

Following is an example of the usage of this method −

def lst = [11, 12, 13, 14];
		
println(lst);
lst.add(15);

println(lst);
lst.add(2,20);

println(lst);

Output

When we run the above program, we will get the following result −

[11, 12, 13, 14] 
[11, 12, 13, 14, 15] 
[11, 12, 20, 13, 14, 15]

Example - Checking Element in List of Strings

Following is an example of the usage of this method −

def lst = ["Apple","Orange","Mango"]; 

println(lst.contains("Apple")); 
println(lst.contains("Peach"));

Output

When we run the above program, we will get the following result −

true 
false

Example - Getting Element from a List of Objects

Following is an example of the usage of this method −

def lst = [new Student(1, "Julie"),new Student(2, "Robert"),new Student(3, "Adam")];

println(lst.get(0));
println(lst.get(2));

class Student {
   int rollNo;
   String name;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = 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 ]
Advertisements