Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 699
kuki1384 Avatar asked Mar 15 '12 13:03

kuki1384


1 Answers

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 );
like image 108
Stan Kurilin Avatar answered Sep 24 '22 22:09

Stan Kurilin