Java intersect, union, join, different lists with predicates
                                        
                    •
                    Java                                    
                Hello, I have 2 lists containing the same objects I want to do anything by using predicates, such as intersect, union, distinct, because I can't use equals for comparison
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 car lists I need to find duplicates in this list, but I can't find id just 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 the second object from carlist1 (new car (2, green))
List similar things
Collection.intersect(carList1,carList2,comparator).
In C #, I will use it to LINQ
Solution
You can use guava for similar thinking
1) Intersect is an operation on a collection, not on a list So you should build them like them
final Set<Car> first = ImmutableSet.of( new Car(1,"blue"),"green") );
Or, if you need a special comparator (mention predicates)
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 method to build two collections
Ratio call intersection
final Set<Car> intersection = Sets.intersection( first,second );
                            The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
                        
                                            
                        THE END
                    
                    
                    
                                                        二维码
                        
                        
                                                
                        