Java 8 streams : Combine properties of two objects which are in ArrayLists into an ArrayList of a third object type

feenix110998 :

I'm new to the Java 8 streams and would appreciate some help in learning.

I have an Arraylist of User objects and and Arraylist of UserCompany objects. The User object has a user_id and associated user information The UserCompany list has the user's Company object but only has the user_id of the User. I would like to create a third object called UserCompanyView that is a combination of the User object and the Company object using Java 8 streams. I have only been able to find examples of two arrays being concatenated or merged , like,:

 Stream.of(list1, list2)
.flatMap(x -> x.stream())
.collect(Collectors.toList());

but nothing where specific properties of the individual lists are used to create a third Object.

the code should :

1) iterate through the UserCompany list

2)Check if the UserCompany user_id matches the User list user_id

3) if 2 is true , create a UserCompanyView object using the User and the UserCompany

4) Add the UserCompanyView from 3 to a new List and return it.

Thanks for viewing this post and taking time to reply

shmosel :

If they don't follow the same order, you'll need to create an ID map first:

Map<Integer, User> usersById = users.stream()
        .collect(Collectors.toMap(User::getUserId, u -> u));

Now you can stream the other list and map each element to its matching User by ID:

List<UserCompanyView> views = userCompanies.stream()
        .map(uc -> new UserCompanyView(usersById.get(uc.getUserId()), uc))
        .collect(Collectors.toList())

If there are UserCompanys without matching Users, you can filter them out by adding this before map():

.filter(uc -> usersById.containsKey(uc.getUserId()))

Guess you like

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