Im trying to use Java 8 streams to combine lists. How can I get a "symmetric difference list" (all object that only exist in one list) from two existing lists. I know how to get an intersect list and also how to get a union list.
In the code below I want the disjoint Cars from the two lists of cars (bigCarList,smallCarList). I expect the result to be a list with the 2 cars ("Toyota Corolla" and "Ford Focus")
Example code:
public void testDisjointLists() {
List<Car> bigCarList = get5DefaultCars();
List<Car> smallCarList = get3DefaultCars();
//Get cars that exists in both lists
List<Car> intersect = bigCarList.stream().filter(smallCarList::contains).collect(Collectors.toList());
//Get all cars in both list as one list
List<Car> union = Stream.concat(bigCarList.stream(), smallCarList.stream()).distinct().collect(Collectors.toList());
//Get all cars that only exist in one list
//List<Car> disjoint = ???
}
public List<Car> get5DefaultCars() {
List<Car> cars = get3DefaultCars();
cars.add(new Car("Toyota Corolla", 2008));
cars.add(new Car("Ford Focus", 2010));
return cars;
}
public List<Car> get3DefaultCars() {
List<Car> cars = new ArrayList<>();
cars.add(new Car("Volvo V70", 1990));
cars.add(new Car("BMW I3", 1999));
cars.add(new Car("Audi A3", 2005));
return cars;
}
class Car {
private int releaseYear;
private String name;
public Car(String name) {
this.name = name;
}
public Car(String name, int releaseYear) {
this.name = name;
this.releaseYear = releaseYear;
}
//Overridden equals() and hashCode()
}
List<Car> disjoint = bigCarList;
? I don't really understand the question. You have two lists A and B, and you want all the elements of the list A. So, just use A. Please clarify. – Otha