java interscect,union,join,带谓词的不同列表

kuk*_*384 7 java union predicate list

您好我有2个包含相同对象的列表.我想通过使用谓词执行任何操作,如intercesct,union,distinct,因为我无法使用equals来进行比较.

例:

class Car{
  public String id;
  public String color;
  public int hashcode(){
    //id field is used for hashcode
  }
  public boolean equals(){
    //id field is used for equals
  }
}
Run Code Online (Sandbox Code Playgroud)

现在我有两个汽车清单.我需要在这个列表中找到重复项,但不能仅通过颜色找到id.

List<Car> carList1 = new ArrayList(){ new Car(1,blue), new Car(2,green)};
List<Car> carList2 = new ArrayList(){ new Car(1,silver), new Car(4,green)};
Run Code Online (Sandbox Code Playgroud)

我需要从carList1找到第二个对象(新车(2,绿色))

列出类似的东西

Collection.intersect(carList1,carList2,comparator).
Run Code Online (Sandbox Code Playgroud)

在C#中我会用它来LINQ.

Sta*_*lin 4

您可以使用Guava进行类似的思考。

1) 相交是对集合的操作,而不是对列表的操作。所以你应该像这样构造它们

final Set<Car> first = ImmutableSet.of( new Car(1, "blue"), new Car(2, "green") );
Run Code Online (Sandbox Code Playgroud)

或者,如果您需要特殊比较器(提到的谓词)

final Set<Car> second = newTreeSet( new Comparator<Car>(){
    public int compare( final Car o1, final Car o2 ){
        return o1.getColor().compare( o2.getColor() );  //return 0 when predicate return true
    }
} );
second.add( new Car(1, "green")  );
Run Code Online (Sandbox Code Playgroud)

UPD: 您应该仅使用一种方法来构造这两个集合。

比调用交集

 final Set<Car> intersection = Sets.intersection( first, second );
Run Code Online (Sandbox Code Playgroud)