groovy / java检查列表交集和组合元素 [英] groovy/java check list intersections and combine elements
本文介绍了groovy / java检查列表交集和组合元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表:
def a = [[14,17,12,5],[14,17 ,12,8,3],[5,2],[9]]
我需要检查交叉点,如果两个列表相交,合并它们。
结果应如下所示:
def b = [ [14,17,12,5,8,3,2],[9]]
即14在第一个子列表中,也在第二个子列表中,并且递归地如此...)
这个任务如何解决?
解决你可以在Groovy中做这样的事情:
def a = [[14,17, (5),(9),(9),(12),(14),(17), >
for(cc in c){
if(n.find {it in cc}!= null){
cc.addAll(n)
cc = cc.unique( )
回报c
}
}
c <<
assert rslt == [[14,17,12,5,8,3,2],[9]]
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?
解决方案
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]]
这篇关于groovy / java检查列表交集和组合元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文