Nesting groovy each{} inside find{} - groovy

I know we cannot return from .each{} closure in groovy like .find{} closure. Still I am curious why the below code execute only first iteration of the .find{}.
def findlist = [1,2,3,4,5]
def eachlist = [7,6,5]
findlist.find
{
int findelem = it
println "findelem : " + findelem
eachlist.each
{
int eachelem = it
println "eachelem : " + eachelem
if(it == findelem)
{
return true
}
return false
}
}
It prints:
findelem : 1
eachelem : 7
eachelem : 6
eachelem : 5
Why find{} exits after first iteration?
PS: I understand this code might not have any practical significance, just curious about groovy behavior.

Because each returns unmodified collection is iterating on. The returned collection evaluates to true, hence find stops after first iteration.
Have a look at the code below:
assert [1, 2].each { println it } == [1,2]
assert [1,2].find { println it; [3, 4].each { e -> println e } }
You need to nest find instead of each.

Just to complete Opal's answer (each returns the collection so it evaluates to true if it is not empty), you can use a local variable inside the find closure to return the found value. Simplifying your code a bit:
assert 5 == findlist.find { findelem ->
println "findelem : " + findelem
boolean found
eachlist.each { eachelem ->
println "eachelem : " + eachelem
found = (eachelem == findelem)
}
found
}
However, there is a nicer and groovier way:
assert 5 == findlist.find { it in eachlist }

Related

groovy map populate with default element

Is there more Groovish way of adding an element to map of lists and initialize default list if not exists?
Or in other words what would be a Groovish way to code the below:
def mylist = [1,2,3,4]
def mymap = [:]
for (num in mylist){
if (num % 2 == 0){
pairity = "even"
} else {
pairity = "odd"
}
if (mymap.containsKey(pairity)){
println("Adding to Even")
mymap[pairity].add(num)
}
else {
println("adding to Odd")
mymap[pairity] = [num]
}
}
print(mymap.toString())
// adding to Odd
// adding to Odd
// Adding to Even
// Adding to Even
// [odd:[1, 3], even:[2, 4]]
You can use withDefault on a map to have automatically generate a value for a missing key on access.
[1,2,3,4].inject([:].withDefault{[]}){ m, i -> m[ i%2==0 ? 'odd' : 'even' ] << i; m }
// => [even:[1, 3], odd:[2, 4]]
You can simply groupby:
def mymap = mylist.groupBy { it % 2 == 0 ? 'even' : 'odd' }
That is effectively using the closure to partition the list on the condition.

I need a shorthand way to combine Maps in groovy with slightly different results than +

NOTE: This can be done as a method call or an operator override pretty easily, I am looking for an intrinsic one-line solution that I don't have to carry around in a library.
When you combine(add) Maps, you get a result like this:
println [a:1,c:3] + [a:2]
// prints {a=2, c=3}
I seem to keep needing results more like:
{a=[1, 2], c=[3]}
In other words, something that combines all the values from identical keys in the Maps.
Is there an operator or simple function call that does this, because doing it myself always seems to break my stride a little. It seems like the * operator might do this nicely, but it doesn't.
Is there an easy way to do this?
Another alternative (adding it to the * operator on Maps)
def a = [ a:1, c:10 ]
def b = [ b:1, a:3 ]
Map.metaClass.multiply = { Map other ->
(delegate.keySet() + other.keySet()).inject( [:].withDefault { [] } ) { m, v ->
if (delegate[v] != null) { m[v] << delegate[v] }
if (other[v] != null) { m[v] << other[v] }
m
}
}
assert a * b == [a:[1, 3], c:[10], b:[1]]
Came up with this as well, but it's late and there are probably better, shorter ways
def a = [ a:1, c:10 ]
def b = [ b:1, a:3 ]
[a,b]*.collect {k,v -> [(k):v]}
.flatten()
.groupBy { it.keySet()[0]}
.inject([:].withDefault{[]}) {m,v->
m << [(v.key):v.value[v.key]]
}
​​
Nothing came to my mind, so I start the bidding with this:
m1 = [a:1, c:666]; m2 = [a:2, b:42]
result = [:].withDefault{[]}
[m1,m2].each{ it.each{ result[it.key] << it.value } }
assert result == [a:[1,2], b:[42], c:[666]]

Update map using findAll and each in groovy

I would like to update values in map in Groovy filling certain criteria. Here is my code:
def m = [:]
m['a'] = 1
m['b'] = 2
m['d'] = 3
m.findAll { it.value > 1}.each {
it.value = 4
}
println m
But the result is following:
[a:1, b:2, d:3]
Is there any way to do it using both findAll and each? Or I must use
m.each {if (it.value>1) it.value=4}
The root cause is findAll returns a new Map instance.
So you could try:
newMap = m.findAll { it.value > 1}.each {
it.value = 4
}
println m //No change
println newMap //This is what you need!
output is
[a:1, b:2, d:3]
[b:4, d:4]
In each case, the values you are iterating with the each are map entries with a pointer to key and value. When you set it.value you are not replacing what is in the map. You are only updating the pointer in the map entry. To actually set the value, you will need to do the following:
m.findAll { it.value > 1 }.each { m[it.key] = 4 }

Groovy: Detecting when being passed arrays

The function f in the following code simply attempts to print out it's arguments and how many it receives. However, it expands array parameters (but not arraylists) as illustrated on the line f(x) // 3. Is there anyway to get f not to expand array parameters, or alternatively at the very least detect that it has happened, and perhaps correct for it. The reason for this is because my "real" f function isn't as trivial and instead passes it's parameters to a given function g, which often isn't a variable parameter function which instead expects an array directly as an argument, and the expansion by f mucks that up.
def f = {
Object... args ->
print "There are: ";
print args.size();
println " arguments and they are: ";
args.each { println it };
println "DONE"
}
def x = new int[2];
x[0] = 1;
x[1] = 2;
f(1,2); // 1
f([1,2]); // 2
f(x); // 3
I doubt there is any clean solution to this, as it behaves as Java varargs. You may test the size of the array inside the closure, or, as in Java, use a method overload:
public class Arraying {
public static void main(String[] args) {
// prints "2"
System.out.println( concat( new Object[] { "a", "b" } ) );
// prints "a". Commenting the second concat(), prints "1"
System.out.println( concat( "a" ) );
// prints "3"
System.out.println( concat( "a", "b", "c" ) );
}
static String concat(Object... args) {
return String.valueOf(args.length);
}
static String concat(Object obj) { return obj.toString(); }
}
If you comment the concat(Object obj) method, all three methods will match the concat(Object... args).
You can use a label for the argument as follow:
def f = {
Object... args ->
print "There are: ";
print args.size();
println " arguments and they are: ";
args.each { println it };
println "DONE"
}
def x = new int[2];
x[0] = 1;
x[1] = 2;
f(1,2); // 1
f([1,2]); // 2
f(a:x); // <--- used label 'a', or anything else
then the output is:
There are: 2 arguments and they are:
1
2
DONE
There are: 1 arguments and they are:
[1, 2]
DONE
There are: 1 arguments and they are:
[a:[1, 2]]
DONE

What is the neatest way to remove all but the last item from a list in groovy?

I've been trying to find a neat way to remove all but the last element from a list in groovy, but all the things I've tried seem a bit overcomplicated. Is there a neater way?
FAILS: java.util.ConcurrentModificationException
void removeAllButLastInPlace(list) {
if(list.size() > 1) {
def remove = list[0..-2]
remove.each { list.remove(it) }
}
}
FAILS: java.lang.CloneNotSupportedException: java.util.ArrayList$SubList
void removeAllButLastInPlace(list) {
if(list.size() > 1) {
def remove = list[0..-2].clone()
remove.each { list.remove(it) }
}
}
WORKS, but list construction seems unnecessary
void removeAllButLastInPlace(list) {
if(list.size() > 1) {
def remove = [] + list[0..-2]
remove.each { list.remove(it) }
}
}
WORKS, but seems a bit arcane
void removeAllButLastInPlace(list) {
(list.size() - 1).times { list.remove(0) }
}
WORKS, perhaps most 'correct'
void removeAllButLastInPlace(list) {
list.retainAll { list.lastIndexOf(it) == list.size() - 1 }
}
The code should fulfil the following tests:
list = []
removeAllButLastInPlace(list)
assert list == []
list = ['a']
removeAllButLastInPlace(list)
assert list == ['a']
list = ['a', 'b']
removeAllButLastInPlace(list)
assert list == ['b']
list = ['a', 'b', 'c']
removeAllButLastInPlace(list)
assert list == ['c']
Rather than mutating an existing list., why not return a new list?
Then you can simply do:
List removeAllButLast( List list ) {
list ? [list[-1]] : []
}
Or:
List removeAllButLastInPlace( List list ) {
list.drop( list.size() - 1 )
}
edit:
You could also use a loop (if you have to have a mutating method)
void removeAllButLastInPlace( List list ) {
while( list.size() > 1 ) list.remove( 0 )
}
void removeAllButLastInPlace( List list ) {
def index = 0
list.reverse(true).retainAll({index++ == 0})
}
I'd go for one of these. My criteria being a) modifying the list in place as stated in your requirement (not returning a new list) and b) succinctness.
I have however made both versions return a reference to the modified list just to simplify the println examples. You could make the return type 'void' if preferred and remove the last 'xs' line from each.
def xs1 = [1, 2, 3, 4, 5]
def xs2 = [9]
def xs3 = []
def keepOnlyLast1(xs) {
while(xs.size() > 1) xs.remove(0)
xs
}
def keepOnlyLast2(xs) {
xs[0 ..< xs.size()-1] = []
xs
}
println "Version 1"
println keepOnlyLast1([] + xs1)
println keepOnlyLast1([] + xs2)
println keepOnlyLast1([] + xs3)
println "Version 2"
println keepOnlyLast2([] + xs1)
println keepOnlyLast2([] + xs2)
println keepOnlyLast2([] + xs3)
/* Sanity check that these methods *really* modify the list. */
println "Sanity Check"
keepOnlyLast1(xs1)
println xs1
keepOnlyLast2(xs2)
println xs2
Aside: I would also go for a more functional style if at all possible (i.e. return a new list rather than modifying the existing one) except that that wasn't what you asked for. Here's an example anyway:
def lastAsList(xs) {
xs.isEmpty() ? [] : [xs[-1]]
}
println lastAsList([1, 2, 3])
println lastAsList([])

Resources