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
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 UserCompany
s without matching User
s, you can filter them out by adding this before map()
:
.filter(uc -> usersById.containsKey(uc.getUserId()))