Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combine two streams and call method

I have a problem how to stream asynchornously and call a method,
e.g.

List<User> users = List.of(user1, user2, user3);
List<Workplace> worklpaces = List.of(workplace1,workplace2,workplace3)

It’s always the same users.size == workplaces.size

we have a function mapping

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public List<UserWithWorkplace> combineUserWithWorkplaceAndType(List<User> users,List<Workplace> 
worklpaces, Type someRandomtype) {

//here is the problem it wont it should be get
//List<UserWithWorkplace>.size == users.size == workplaces.size


return users.stream().flatMap(user -> 
                              worklpaces.stream()
                              .map(worklpace -> mapping(user,worklpace, someRandomtype)))
                              .toList()
}


private UserWithWorkplace mapping( User user, Workplace workplace,Type someRandomtype){

//cominging and returning user with workplace
}

How to achieve that result?

>Solution :

Assuming you want to create pairs of (user, workplace) from two separate users an workplaces streams, this operation is normally called "zipping".

Guava library provide Streams.zip(Stream, Steam, Function) method for this. In your case the code would look like:

Stream<UserWithWorkplace> zipped = Streams.zip(
    users.stream(), 
    worklpaces.stream(), 
    (u, w) -> this.mapping(u, w, someRandomtype));

However your example code uses List and not Stream to represent data. I’m not sure if you have to use Java streams for this, a simple for loop with i index might be easier.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading