Loading...

Tuesday, October 2, 2012

Groovy Goodness: Drop or Take Elements with Condition

In Groovy we can use the drop() and take() methods to get elements from a collection or String object. Since Groovy 1.8.7 we also can use the dropWhile() and takeWhile() methods and use a closure to define a condition to stop dropping or taking elements. With the dropWhile() method we drop elements or characters until the condition in the closure is true. And the takeWhile() method returns elements from a collection or characters from a String until the condition of the closure is true.

In the following example we see how we can use the methods:

def s = "Groovy Rocks!"

assert s.takeWhile { it != 'R' } == 'Groovy '
assert s.dropWhile { it != 'R' } == 'Rocks!'


def list = 0..10

assert 0..4 == list.takeWhile { it < 5 }
assert 5..10 == list.dropWhile { it < 5 }


def m = [name: 'mrhaki', loves: 'Groovy', worksAt: 'JDriven']

assert [name: 'mrhaki'] == m.takeWhile { key, value -> key.length() == 4 }
assert [loves: 'Groovy', worksAt: 'JDriven'] == m.dropWhile { it.key == 'name' }

(Code is written with Groovy 2.0.4)

2 comments:

Alessandro Carraro said...

I'm curious how those methods works with Maps or Sets.
Since it iterate on a collection, and stops when a condition is met, order does matter - a LOT!

if m (as the previous example) had 2 keys whose length was 4, what the code return?
m.takeWhile { key, value -> key.length() == 4 }

Hubert Klein Ikkink said...

@Allessandro Garraro: You are right, order is very important for this methods. If the map had two keys with length 4, but the second one was the last element of the Map, than only the first will be returned. We could add a sort(); m.sort { it.key.length() }.takeWhile { key, value -> key.length() == 4 } to get all elements with key length 4. But then we can also use findAll{}.

Post a Comment