Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - List shuffle(Random random) method



Description

Groovy List shuffle(Random random) method reorders the current list elements in the random order using given Random Instance.

Syntax

public void shuffle(Random random)

Parameters

random − a random instance

Return Value

The shuffled list using given Random instance.

Example - Shuffling a List of Integers

Following is an example of the usage of this method −

main.groovy

def lst = [11, 12, 13, 14]; 

lst.shuffle(new Random()); 
println(lst);  

Output

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

[12, 14, 13, 11]

Example - Shuffling a List of Strings

Following is an example of the usage of this method −

main.groovy

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

lst.shuffle(new Random()); 
println(lst);  

Output

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

[Peach, Mango, Apple, Orange]

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

lst.shuffle(new Random()); 
println(lst);     

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 −

[[ 2, Robert ], [ 1, Julie ], [ 3, Adam ]]
groovy_lists.htm
Advertisements