Two Interesting methods in Groovy 2.0 : takeWhile and dropWhile
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.
[java]
List marks = [2,1,4,8,5,7,9,12]
println marks.takeWhile{it < 6}
//Output: [2, 1, 4]
[/java]
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:
[java]
Map m = ["groovy":8,"grails":9,"database":6,"java":1,"gorm":7,"html":2,"javascript":3]
println m.takeWhile{it.value > 7 }
//Output: [groovy:8, grails:9]
println m.takeWhile{it.key != "html" }
//Output: [groovy:8, grails:9, database:6, java:1, gorm:7]
[/java]
Using takeWhile method with char sequence:
[java]
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
[/java]
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.
[java]
List marks = [‘c’,’g’,’f’,’n’,’b’,’h’,’y’]
println marks.dropWhile{it < ‘m’} // It will print [n, b, h, y]
[/java]
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
[java]
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: [html:2, javascript:3]
[/java]
Using takeWhile method with char sequence
[java]
String line = "Grails is a web framework based on the Groovy language."
println line.dropWhile { it < ‘x’ } //y language.
[/java]
Divya Setia
divya@intelligrape.com
https://twitter.com/divs157
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}
first scenario should include 5
List marks = [2,1,4,8,5,7,9,12]
println marks.takeWhile{it < 6}
//Output: [2, 1, 4]
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!
In the last and in the second example, isn’t “x” wrong? I excpected a “v” as char inside closure.