Matching and setting object variable from a list to a different object list

Stefza :

Trying to figure out the best way to match an Objects variable that is in a list with a different type of Object Variable in a list. Once the match has been found I would like to set a different variable within that first Object to another Object variable it matched with. The best way to explain this would be like this:

I have a List<Cat> cats and cat has the variables id, size, breed, name, vetId and vetName.

I also have a List<Vet> vets and vets have variables id, address, phone and name.

The list of cats has a vetId but vetName is null, I need to somehow add the name from the vets list.

I need a quick and efficient way to do this. I'm not so skilled with new Java 8 stuff but i'm sure there will be a quick way of doing this with it.

ETO :

Assuming you have two lists List<Cat> cats and List<Vet> vets

You can achieve what you need using Stream API:

// Build map of (vetId -> vetName) pairs
Map<Long, String> vetMap = vets.stream().collect(toMap(Vet::getId, Vet::getName));
// Update cats with proper vet names
cats.forEach(cat -> cat.setVetName(vetMap.get(cat.getVetId())));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=306595&siteId=1