Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner join of two ArrayLists purely in Java

Tags:

java

arraylist

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?

like image 679
Ondrej Tokar Avatar asked Sep 11 '25 21:09

Ondrej Tokar


1 Answers

Assuming you:

  • use Java 8
  • you have 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:

  • creates a java.util.Map instance where the key is owner id and the value is the owner instance
  • then iterates through the cars and creates Result instances, which contain a reference to the car and the owner, which is looked up using the previously created map
like image 132
Adam Siemion Avatar answered Sep 13 '25 11:09

Adam Siemion