Find something in Groovy Collection
I likes groovy because you can create such very complex object easy. But, if you want explore them, it can be such a discovery or/and a nightmare …
The problem
My initial source code is :
def items = [] def item1 = [key: 1, value: 10, name: "victor"] items.add item1 // Then add multiple item with the same structure.
How can I found an item in my List of Map ?
What Groovy provides ?
Simple collection iteration
def fibList = [1, 1, 2, 3, 5, 8, 13] fibList.each { println it } // prints all of the numbers in the list
any
If you need to find out if any element of the collection meets the condition.
def fibList = [1, 1, 2, 3, 5, 8, 13] assert fibList.any { it == 3 } assert fibList.any { it - 2 > 10 }
This is pretty much equivalent to a Java construct
boolean any(List list, Condition cond) for (E e : list) { if (cond.meets(e)) { return true; } } return false; }
every
If you need to find out if any element of the collection meets the condition.
def fibList = [1, 1, 2, 3, 5, 8, 13] assert fibList.every { it > 0 }
This is pretty much equivalent to a Java construct
boolean every(List list, Condition cond) for (E e : list) { if (!cond.meets(e)) { return false; } } return true; }
collect
If you need to create a new collection that contains each element of the original collection transformed in some way.
def fibList = [1, 1, 2, 3, 5, 8, 13] assert fibList.collect { it - 1 } == [0, 0, 1, 2, 4, 7, 12]
This is pretty much equivalent to a Java construct
List every(List list, Command command) List result = new ArrayList(list.size()); for (E e : list) { result.add(command(e)); } return result; }
findAll
If you need to create a new collection that contains all elements that meet the condition.
def fibList = [1, 1, 2, 3, 5, 8, 13] assert fibList.findAll { it > 1 && it < 5 } == [2, 3]
This is pretty much equivalent to a Java construct
List findAll(List list, Condition cond) List result = new ArrayList(list.size()); for (E e : list) { if (!cond.meets(e)) { result.add(e); } } return result; }
find
If you need to find first element that matches the condition.
def fibList = [1, 1, 2, 3, 5, 8, 13] assert fibList.find { it > 1 } == 2
This is pretty much equivalent to a Java construct
E findAll(List list, Condition cond) for (E e : list) { if (!cond.meets(e)) { return e; } } return null; }
The solution
Let's back to my initial problem. I can find what I want by using :
source: http://hanuska.blogspot.com/2008/12/easy-groovy-iteration.html