Two Interesting methods in Groovy 2.0 : takeWhile and dropWhile

12 / Sep / 2012 by Divya Setia 4 comments

Today I found two very interesting methods: takeWhile and dropWhile. The names itself reveals their work i.e. takeWhile (consider while some condition is true) and dropWhile (ignore while some condition is true).

Although, these methods have been added to Groovy 1.8.7, but for character sequence, these methods are supported in Groovy 2.0 only.

The takeWhile method considers each element one by one in order of definition till the condition does not fail.
e.g.

List marks = [2,1,4,8,5,7,9,12]

println marks.takeWhile{it < 6} 

//Output: [2, 1, 4]    

As soon as takeWhile method found an element greater than 6 (in above example) by processing elements in the order of definition, it stopped considering more elements.

Using takeWhile method with Map:

Map m  = ["groovy":8,"grails":9,"database":6,"java":1,"gorm":7,"html":2,"javascript":3]

println m.takeWhile{it.value > 7 } 

//Output:  1

println m.takeWhile{it.key != "html" } 

//Output: 1

Using takeWhile method with char sequence:

String line = "Grails is a web framework based on the Groovy language."

println line.takeWhile { it < 'x' }  

//Output: Grails is a web framework based on the Groov

The takeWhile method considers each character in character sequence one by one till the condition does not fail.

Moving on to dropWhile method, It ignores all the elements in order of definition till the condition does not meet.

List marks = ['c','g','f','n','b','h','y']

println marks.dropWhile{it < 'm'} // It will print [n, b, h, y]

In above example, the dropWhile method ignored all the list elements(‘c’,’g’,’f’,’n’) till the condition did not meet.

Using dropWhile method with map

Map m  = ["groovy":4,"grails":6,"database":9,"java":1,"gorm":7,"html":2,"javascript":3]

println m.dropWhile{it.value < 7 } 

// Output: [database:9, java:1, gorm:7, html:2, javascript:3]

println m.dropWhile{it.key != "html" } 

// Output: 1

Using takeWhile method with char sequence

String line = "Grails is a web framework based on the Groovy language."

println line.dropWhile { it < 'x' }  //y language.

Divya Setia
divya@intelligrape.com
https://twitter.com/divs157

FOUND THIS USEFUL? SHARE IT

comments (4)

  1. Douglas Smith

    I am not sure why takeWhile an dropWhile are needed. The *find* method does exactly the same thing.

    List marks = [2,1,4,8,5,7,9,12]

    println marks.find{it = 6}

    Reply
  2. Nick

    first scenario should include 5

    List marks = [2,1,4,8,5,7,9,12]

    println marks.takeWhile{it < 6}

    //Output: [2, 1, 4]

    Reply
  3. Jonatas Emidio

    Hi!
    Very nice post!
    I’m new in groovy so I need some more informations about this feature…

    What’s the diference between takeWhile and findAll!
    I did some tests and recived the same answer!

    Reply

Leave a comment -