Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - List getAt(int idx) method



Description

Groovy List getAt(int idx) method returns the element at given index.

Syntax

public List getAt(int idx)

Parameters

idx − index at which element is to be retrieved.

Return Value

The value at the given index.

Example - Getting an item from a List of Integers

Following is an example of the usage of this method −

main.groovy

def lst = [1,2, 3, 4, 5]
def item = lst.getAt(2)

println(item)

Output

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

3

Example - Getting an item from a List of Strings

Following is an example of the usage of this method −

main.groovy

def lst = ["Apple","Mango","Orange", "Papaya", "Peach"]
def item = lst.getAt(2)

println(item)

Output

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

Orange

Example - Getting an item from a List 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 item = lst.getAt(2)

println(item)

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 −

[ 3, Adam ]
groovy_lists.htm
Advertisements