如何在groovy中找到数组元素的差异?
如何找到groovy中映射的数组元素的差异?
def first = [['fruit':'grapes', 'drink':'tea'],
['fruit':'apple', 'drink':'milk']]
def second = [['fruit':'grapes', 'drink':'tea'],
['fruit':'melon', 'drink':'milk'],
['fruit':'coconut', 'drink':'soda']]
def diff = first.minus(second)
echo "diff ${diff}
实际输出为
diff []
预期输出为
[['fruit':'melon'],['fruit':'coconut', 'drink':'soda']]
How to find difference of array elements that are maps in groovy?
def first = [['fruit':'grapes', 'drink':'tea'],
['fruit':'apple', 'drink':'milk']]
def second = [['fruit':'grapes', 'drink':'tea'],
['fruit':'melon', 'drink':'milk'],
['fruit':'coconut', 'drink':'soda']]
def diff = first.minus(second)
echo "diff ${diff}
Actual output is
diff []
Expected output is
[['fruit':'melon'],['fruit':'coconut', 'drink':'soda']]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您想要执行此操作并查找差异时遇到的一个问题是 - 当您比较元素时您优先考虑哪个数组?鉴于您最初的问题,看来您优先考虑较大的一个,因为所需输出中的
fruit
是melon
(但也可能是apple
)。考虑到这一点,这是我为您创建的解决方案,它优先考虑更大的数组(您也可以在这里测试它 http: //tpcg.io/03UE84):
One problem you have when you want to do this and find the diff is - which array do you prioritize when you compare the elements? Given your original question, it looks like you prioritize the bigger one as the
fruit
ismelon
in your required output (but could've beenapple
).Considering this, here is the solution I've created for you which prioritises the bigger array (You can test it here as well http://tpcg.io/03UE84):
因此,我在 groovysh 中尝试了您的代码,并得到了接近您正在寻找的答案的内容:
输出:
minus
方法将依赖于顺序。它不会返回第二个列表中不在第一个列表中的项目。它只会返回第一个列表中的项目。因此“melon”、“coconut”不会与first.minus(second)
一起出现。当然,明显的问题是drink: milk
出现,因为它包含在地图中,其中 1 个成员不在第一个地图中,因此它包含该地图的所有成员。这就是minus
方法的工作原理,因此它不能成为解决方案。因此,这是另一种方法,可以满足您的期望(但它仍然依赖于顺序):
输出:
So I tried your code in groovysh and got something close to the answer you were looking for:
Output:
The
minus
method is going to be order dependent. It won't return items in the second list that aren't in the first. It's only going to return the items that are only in the first list. So 'melon', 'coconut' aren't going to show up withfirst.minus(second)
. Of course the obvious issue is thatdrink: milk
shows up because it is contained within maps where 1 member isn't in the first so it includes all members of that map. That's just howminus
method works so it can't be a solution.So here is another method that does what you expect (but it's still order dependent):
Output:
这对我来说有效,
输出:
This works on my end,
The output: