Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - List get() method



Description

Groovy List get() method returns the element at the specified position in this List.

Syntax

Object get(int index)

Parameters

Index − The index at which the value needs to be returned.

Return Value

The value at the index position in the list.

Example - Getting Element from a List of Integers

Following is an example of the usage of this method −

main.groovy

def lst = [11, 12, 13, 14];
println(lst.get(0));
println(lst.get(2));

Output

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

11 
13

Example - Getting Element from a List of Strings

Following is an example of the usage of this method −

main.groovy

def lst = ["Apple","Orange","Mango"];
println(lst.get(0));
println(lst.get(2));

Output

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

Apple
Mango

Example - Getting Element 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")];

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 ]
groovy_lists.htm
Advertisements