Is there a way to do the inner join of two ArrayLists of two different objects based on one field?
Let's say I've got:
ArrayList<Car>
ArrayList<Owner>
Car would have these attributes: Weight, Top speed, OwnerId
Owner would have these attributes: Name, Age, Id
The result would be an ArrayList<Result>
with attributes: Weight, Top speed, Id, Name, Age
And I want to make an inner join of these 2 based on a single field called Id
. Is there any optimal way to do that without using a database or nested loops?
Assuming you:
List<Car> cars
and List<Owner> owners
Result
has a constructor that takes a Car
and an Owner
This is how you can get List<Result>
:
final Map<Integer, Owner> ownersById = owners.stream()
.collect(Collectors.toMap(k -> k.id, k -> k));
final List<Result> results = cars.stream()
.map(car -> new Result(car, ownersById.get(car.OwnerId)))
.collect(Collectors.toList());
Which:
java.util.Map
instance where the key is owner id and the value is the owner instanceResult
instances, which contain a reference to the car and the owner, which is looked up using the previously created mapIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With