How to extract a sub list in Groovy

Groovy has a built-in method on the List type to return a view of the portion of a List object between the specified fromIndex, inclusive, and toIndex, exclusive. The method can be applicable for the list of objects from different types not only primitive types.

Table of Contents

Syntax

List subList(int fromIndex, int toIndex)

  • fromIndex: Starting index of the list
  • toIndex: Ending index of the list

Return Value

The list of range values from specified starting to ending index.

Examples

Following is an example of the usage of this method.

class SubListDemo { 
   static void main(String[] args) { 
      def rint = 1..10; 
        
      println(rint.subList(1,4)); 
      println(rint.subList(4,8)); 
   } 
}

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

[2, 3, 4] 
[5, 6, 7, 8]

Now we can try a little bit complex example with a list of Java class objects.

class Person {
    private String name
}

List myFamily =["Tung", "Hue", "Khang", "Phu"].collect {
    new Person(name: it)
}

println myFamily*.name
println myFamily.subList(0, 2)*.name

The output of the tiny snippet above is:

[Tung, Hue, Khang, Phu]
[Tung, Hue]

Voilà! Hope this helps your life easier!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.