A
A
askalidov2022-03-20 17:19:30
Java
askalidov, 2022-03-20 17:19:30

How to merge 2 ArrayList into 1 by matching value (id)?

There are 2 ArrayLists

List<Product> productListWithUrlName = new ArrayList<>();
List<Product> productListWithPrice = new ArrayList<>();

The first contains products, they have an id, a name, and a link to each. In the second - the same products, they have id (they match the id from the first list) and their cost. It is necessary to combine them by this very id.

Example:
In the first list:
Product[id=1, url="SomeURL", name="Product1"],
in the second:
Product[id=1, price=1000].

The output should be accordingly:
Product[id=1, url="SomeURL", name="Product1", price=1000].

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2022-03-20
@askalidov

Good afternoon!
One possible solution:
- create a Map<Long, Product>
Long - product id
- Add the elements of the first List to the Map.
- Iterate over the second List. Inside the loop, get the item from the Map by the object ID from the second List.
- Use setters to assign values.
- If there is no product with this ID, then add it to the Map
Here, a similar question - https://stackoverflow.com/questions/12670756/join-...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question