为什么在Groovy中,当我创建两个列表时,如果我执行a.intersect( B)和b.intersect( A)有什么不同:
def list1 = ["hello", "world", "world"];
def list2 = ["world", "world", "world"];
println( "Intersect list1 with list2: " + list1.intersect( list2 ) );
println( "Intersect list2 with list1: " + list2.intersect( list1) );痕迹:
Intersect list1 with list2: [world, world, world]
Intersect list2 with list1: [world, world](您可以在这里复制它:如果您想测试它,可以复制http://groovyconsole.appspot.com/ )
如果数组都包含唯一的元素,那么它可以正常工作。一旦开始添加重复项,就会变得很奇怪:
def list1 = ["hello", "world", "test", "test"];
def list2 = ["world", "world", "world", "test"];
println( "Intersect list1 with list2: " + list1.intersect( list2 ) );
println( "Intersect list2 with list1: " + list2.intersect( list1 ) );痕迹:
Intersect list1 with list2: [world, world, world, test]
Intersect list2 with list1: [world, test, test]我认为intersect()的全部目的是为您提供公共元素,所以您把它们放在哪一个顺序并不重要?
如果不是这样的话,我如何才能只获得公共元素(期望数组中的重复元素)。示例1应该返回["world", "world"],示例2应该返回["world", "test"]
编辑
为了澄清一点,这段代码应该测试用户数据是否仍然是相同的(假设它们在某件事情的中间断开连接,并且我们希望确保数据没有被篡改,或者处于与以前相同的状态)。
列表的顺序不能保证(用户可以重新排序,但在技术上仍然是“相同的”),重复是可能的。
因此,类似于:["one", "one", "two"]应该与["two", "one", "one"]匹配,而列表中的任何添加或数据的更改都不应该匹配。
发布于 2011-09-12 11:34:53
如果您查看the source for Collection.intersect,可以看到该方法的逻辑遵循以下流程:
对于两个集合,left和right
right
left和right如果left小于left,则将left和right转换为一个集合(如果right中存在每个元素,则删除leftSet中的每个元素,然后将其添加到结果
G 217中)。
所以,对于你最后的两个例子;
def array1 = ["hello", "world", "test", "test"]
def array2 = ["world", "world", "world", "test"]如果我们在Groovy中编写了相同的算法,array1.intersect( array2 )会给出:
leftSet = new TreeSet( array1 ) // both same size, so no swap
// leftSet = [ 'hello', 'world', 'test' ]
right = array2
result = right.findAll { e -> leftSet.contains( e ) }它(如果您运行它),您可以看到意味着结果具有[world, world, world, test]值(正如您发现的那样)。这是因为right中的每个元素都可以在leftSet中找到。
不知道为什么第一个示例应该返回["world","world"] .
以后..。
所以,我认为你们要寻找的是这样的东西:
def array1 = ["hello", "world", "test", "test"]
def array2 = ["world", "world", "world", "test"]
def intersect1 = array1.intersect( array2 ) as TreeSet
def intersect2 = array2.intersect( array1 ) as TreeSet
assert intersect1 == intersect2为了处理集合中的重复项,intersect1和intersect2将等于
[test, world]晚些时候
我相信这能做你想做的:
[array1,array2]*.groupBy{it}.with { a, b -> assert a == b }https://stackoverflow.com/questions/7386978
复制相似问题