简体   繁体   中英

Combine two streams and call method

I have a problem how to stream asynchornously and call a method, eg

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

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?

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.

What you're describing is a zipping operation.

If using Google Guava, you can do this to combine them:

Streams.zip(users.stream(), workplaces.stream(), (user, workplace) -> mapping(user, workplace, someType))

You can also find some other implementations of this operation described here

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