问题
I have a list:
def a = [[14, 17, 12, 5], [14, 17, 12, 8, 3], [5, 2], [9]]
I need to check intersections and if two lists intersect, combine them.
The result should be as follows:
def b = [[14, 17, 12, 5, 8, 3, 2], [9]]
(i.e 14 is in first sublist, which is also in second sublist, and recursively so on...) How this task can be solved?
回答1:
You can do something like this in Groovy:
def a = [[14, 17, 12, 5], [14, 17, 12, 8, 3], [5, 2], [9]]
def rslt = a.inject( [ ] ) { c, n ->
for( cc in c ) {
if( n.find { it in cc } != null ) {
cc.addAll( n )
cc = cc.unique()
return c
}
}
c << n
}
assert rslt == [[14, 17, 12, 5, 8, 3, 2], [9]]
回答2:
Here is another example using some of Groovy's set "inspired" methods on lists
def a = [[14, 17, 12, 5], [14, 17, 12, 8, 3], [5, 2], [9]]
def res = a.inject([]){ acc,val ->
def isect = acc.find{ val.intersect(it)}?.with{ it.addAll(val - it) }
!isect ? acc << val : acc
}
assert res.containsAll([[14, 17, 12, 5, 8, 3, 2], [9]])
来源:https://stackoverflow.com/questions/15816396/groovy-java-check-list-intersections-and-combine-elements