How about this?
[0, 1, 2, 3, 4, 2, 1].groupBy().each { k, v ->
if (v.size() > 1) {
println "Warning: multiple $k detected"
println k
}
}
Question
I have a List like [0, 1, 2, 3, 4, 2, 1]
and i want to print a warning message for each tuple of elements in this list that are equal. So given the list above i would like to do something like
[0, 1, 2, 3, 4, 2, 1].someMethodIDontKnow { Int num, List owner ->
if(owner.contains(num)) println "warning, multiple "+ num +" detected"
println it
}
I can of course save the list and then do it like that:
List<Int> numlist = [0, 1, 2, 3, 4, 2, 1]
numlist.each {
if (numList.contains(it)) println "warning, multiple "+ it +" detected"
println it
}
But that is not as concise as the code before, especially when ithappens in a row of other calls like that:
List somelist
//...
somelist
.findAll{...}
.intersect{...}
//check for some warnings here
.collect{...}
.unique{...}
I would like to avoid assigning the list to a variable if i can do it differently.
Is there maybe some collection method that slipped through my eyes?
Solution
How about this?
[0, 1, 2, 3, 4, 2, 1].groupBy().each { k, v ->
if (v.size() > 1) {
println "Warning: multiple $k detected"
println k
}
}