java InterSCET、union、join、带谓词的不同列表

java InterSCET、union、join、带谓词的不同列表,java,list,union,predicate,Java,List,Union,Predicate,你好,我有两个包含相同对象的列表。我想通过使用谓词执行任何操作,如intercesct、union、distinct,因为我无法使用equals to comparison 例如: class Car{ public String id; public String color; public int hashcode(){ //id field is used for hashcode } public boolean equals(){ //id fiel

你好,我有两个包含相同对象的列表。我想通过使用谓词执行任何操作,如intercesct、union、distinct,因为我无法使用equals to comparison

例如:

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
  }
}
现在我有两张汽车清单。我需要在这个列表中找到重复项,但不是按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)};

在C#中,我将使用LINQ。

有一个名为Apache Functor Commons的库,它支持谓词等

还有一种番石榴,一位评论者指出:


您可以使用Comparator编写自己的代码,但要执行诸如intersect、join等操作,只需使用这些库中的一个就更容易了。

您可以使用类似的方法进行思考

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

final Set<Car> first = ImmutableSet.of( new Car(1, "blue"), new Car(2, "green") );
final Set first=ImmutableSet.of(新车(1,“蓝色”)、新车(2,“绿色”);
或者,如果您需要特殊的比较器(前面提到的谓词)

final Set second=newTreeSet(新比较器(){
公共int比较(最终车辆o1,最终车辆o2){
返回o1.getColor().compare(o2.getColor());//当谓词返回true时返回0
}
} );
第二,添加(新车(1,“绿色”);
UPD:您应该只使用一种方法来构造两个集合

而不是呼叫交叉口

 final Set<Car> intersection = Sets.intersection( first, second );
final Set intersection=Set.intersection(第一、第二);

你说的“谓词”是什么意思?如果要比较两个对象以确定是否相等,可以使用Comparator接口,如果对象相等,该接口将返回0。这里:没有用于此的库方法。你必须自己去做。类似的问题:来自集合的Javadoc。交集:“,如果集合1和集合2是基于不同等价关系的集合(如HashSet、TreeSet和IdentityHashMap的键集都是),那么结果是未定义的。”@Louis Wasserman,我刚刚展示了两种构造集合的方法。答案已更新,请澄清。您确定TreeSet方法有效吗?在javadocs()中,交叉点似乎依赖于contains方法,而contains方法又依赖于所包含对象的equals方法。
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")  );
 final Set<Car> intersection = Sets.intersection( first, second );