- Groovy Tutorial
- Groovy - Home
- Groovy - Overview
- Groovy - Environment
- Groovy - Basic Syntax
- Groovy - Data Types
- Groovy - Variables
- Groovy - Optionals
- Groovy - Numbers
- Groovy - Strings
- Groovy - Ranges
- Groovy - Lists
- Groovy - Maps
- Groovy - Dates & Times
Groovy Operators
- Groovy - Operators
- Groovy - Arithmetic Operators
- Groovy - Assignment Operators
- Groovy - Relational Operators
- Groovy - Logical Operators
- Groovy - Bitwise Operators
- Groovy - Spaceship Operator
- Groovy - in Operator
- Groovy - Elvis Operator
- Groovy - Safe Navigation Operator
- Groovy Operator Precedence & Associativity
Control Statements
- Groovy - Decision Making
- Groovy - If Else Statement
- Groovy - Switch Statement
- Groovy - Loops
- Groovy - For Loop
- Groovy - For-in Loop
- Groovy - While Loop
- Groovy - Do While Loop
- Groovy - Break Statement
- Groovy - Continue Statement
Groovy File Handling
- Groovy - File I/O
- Java - Create a File
- Java - Write to File
- Java - Append to File
- Java - Read Files
- Java - Delete Files
- Java - File Properties
- Java - File Existence and Type
- Java - File Size
- Java - File Permissions
- Java - Directories
- Java - Listing Directories
- Java - Filtering Files/Directories
- Java - Deleting Directories
- Java - Renaming Files/Directories
Groovy Error & Exceptions
- Groovy - Exception Handling
- Groovy - try-catch Block
- Groovy - try-with-resources
- Groovy - Multi-catch Block
- Groovy - Nested try Block
- Groovy - Finally Block
- Groovy - throw Exception
- Groovy - Exception Propagation
- Groovy - Built-in Exceptions
- Groovy - Custom Exception
Groovy Multithreading
- groovy - Multithreading
- groovy - Thread Life Cycle
- groovy - Creating a Thread
- groovy - Starting a Thread
- groovy - Joining Threads
- groovy - Naming Thread
- groovy - Thread Scheduler
- groovy - Thread Pools
- groovy - Main Thread
- groovy - Thread Priority
- groovy - Daemon Threads
- groovy - Shutdown Hook
Groovy Synchronization
- groovy - Synchronization
- groovy - Block Synchronization
- groovy - Static Synchronization
- groovy - Inter-thread Communication
- groovy - Thread Deadlock
- groovy - Interrupting a Thread
- groovy - Thread Control
- groovy - Reentrant Monitor
- Groovy - Methods
- Groovy - Methods
- Groovy - Optional parenthesis
- Groovy - Named Arguments
- Groovy - Closures as Arguments
- Groovy - Method Overloading
- Groovy - Method Scope and Visibility
- Groovy - isCase Method
- Groovy - Implicit Return
- Groovy - Variable Arguments
- Groovy - Regular Expressions
- Groovy - Regular Expressions
- Groovy - Defining Regular Expressions
- Groovy - Matcher Object
- Groovy - Regex Tasks
- Groovy - XML
- Groovy - XML
- Groovy - Parsing XML
- Groovy - Creating XML
- Groovy - Modifying XML
- Groovy - Querying XML
- Groovy - Simplified Notation
- Groovy - Closure based Querying
- Groovy - Closure based Creation
- Groovy - JSON
- Groovy - JSON
- Groovy - Parsing JSON
- Groovy - Creating JSON using JsonOutput
- Groovy - Creating JSON using JsonBuilder
- Groovy - Modifying JSON
- Groovy - Error Handling
- Groovy - Handling JSON Arrays
- Groovy - JSON Array Operations
- Groovy - JSON Objects
- Groovy - JSON Object Operations
- Groovy - Generics
- Groovy - Generics
- Groovy - Declaring Generic Types
- Groovy - Bound Type Parameters
- Groovy - Wild Cards
- Groovy - Miscellaneous
- Groovy - Object Oriented
- Groovy - Closures
- Groovy - Annotations
- Groovy - JMX
- Groovy - DSLS
- Groovy - Database
- Groovy - Builders
- Groovy - Command Line
- Groovy - Unit Testing
- Groovy - Template Engines
- Groovy - Meta Object Programming
- Groovy Useful Resources
- Groovy - Quick Guide
- Groovy - Useful Resources
- Groovy - Discussion
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 ]