Search code examples
javaasynchronousstreamflatmap

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

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.