List 在Groovy中,从一个对象列表中减去另一个对象列表的最佳方法是什么?

List 在Groovy中,从一个对象列表中减去另一个对象列表的最佳方法是什么?,list,groovy,intersect,List,Groovy,Intersect,当元素是对象时,有没有更常规的方法从一个列表中减去另一个列表?我想也许有一种方法可以使用负号,但我想不出来。这就是我所拥有的: class item1 { int foo int getFoo(){return foo} public item1(id_in){ foo = id_in } } def list1 = [new item1(10),new item1(11),new item1(13)] def list2 = [new item1(11),new item1(12

当元素是对象时,有没有更常规的方法从一个列表中减去另一个列表?我想也许有一种方法可以使用负号,但我想不出来。这就是我所拥有的:

class item1 {
  int foo
  int getFoo(){return foo}
  public item1(id_in){ foo = id_in }
}

def list1 = [new item1(10),new item1(11),new item1(13)]
def list2 = [new item1(11),new item1(12),new item1(14)]

// list3 = list2 - list1
def list3 = list2.findAll{ !(it.foo in list1.collect{it.foo}) }
// works
assert list3.collect{it.foo} == [12,14]

这真的很好,但我只是好奇是否有更好的方法。非常相似,但寻找交叉点(巧合的是,几小时前刚刚发布),但我认为前提是对象具有ID属性。这就是我使用foo属性的原因——我不希望解决方案需要一些与“id”相关的grails,如mojo(如果存在这样的东西))。

您应该能够做到:

@groovy.transform.EqualsAndHashCode
class Item1 {
    int foo
    Item1(int too) {
        this.foo = too
    }
}

def list1 = [new Item1(10), new Item1(11), new Item1(13)]
def list2 = [new Item1(11), new Item1(12), new Item1(14)]

def foos = (list2 - list1).foo

你不能实现hashCode和equals吗?或者用@EqualsAndHashCode(list2-list1)注释类。foo将按照@tim_yates的回答进行操作,但还要注意,在原始解决方案中,collect是多余的。您可以简单地说list1*.foo。它会表现得更好。