简体   繁体   中英

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

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

In order for it to perform, you start by building a Map of user_id to User object.

Using streams, you'd do it like this:

List<User> users = // built elsewhere

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

Then you iterate and UserCompany objects, lookup the User object, and create the UserCompanyView object, adding them to a List .

Using streams, you'd do it like this:

List<UserCompany> userCompanies = // built elsewhere

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

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()))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM