java interscect, union, join, distinct lists with predicate

Hello I have 2 lists that contains the same objects. I would like to perform any operation like intercesct, union, distinct by using predicate because I am unable to use equals to comparision.

Example:

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
  }
}

Now I have two lists of Cars. I need to find duplicates in this lists but not by id only by color.

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)};

I need to find second object from carList1 (new Car(2,green))

List Something similar to

Collection.intersect(carList1,carList2,comparator).

In C# I would use for it LINQ.


You can do similar think using Guava.

1) intersect is operation on sets, not on lists. So you should construct them like

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

or, if you need special comparator ( predicate mentioned )

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")  );

UPD: You should use only one way to construct both sets.

Than call intersection

 final Set<Car> intersection = Sets.intersection( first, second );

There is a library for this called Apache Functor Commons that supports Predicates, etc.

http://commons.apache.org/functor/

There is also Guava which one of the commenters pointed to:

http://code.google.com/p/guava-libraries/

You could write your own using Comparator, but to do things like intersect, join, etc its easier just to use one of these libraries.

链接地址: http://www.djcxy.com/p/58210.html

上一篇: .NET和COM互操作性:从.NET客户端发布COM

下一篇: java interscect,union,join,带谓词的不同列表